項目快結束了,人清閑了,寫寫小工具,嘿嘿……
復制文件
/** * 復制文件到目錄 <功能詳細描述> * * @param srcPath 文件絕對路徑 * @param destDirPath 目標文件夾絕對路徑 * @throws Exception * @see [類、類#方法、類#成員] */ public static void copyFile(String srcPath, String destDirPath) throws Exception { File srcfile = new File(srcPath); File destDir = new File(destDirPath); InputStream is = null; OutputStream os = null; int ret = 0; // 源文件存在 if (srcfile.exists() && destDir.exists() && destDir.isDirectory()) { try { is = new FileInputStream(srcfile); String destFile = destDirPath + File.separator + srcfile.getName(); os = new FileOutputStream(new File(destFile)); byte[] buffer = new byte[1024]; while ((ret = is.read(buffer)) != -1) { os.write(buffer, 0, ret); // 此處不能用os.write(buffer),當讀取最后的字節小於1024時,會多寫; // ret是讀取的字節數 } os.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); throw new Exception(""); } catch (IOException e) { e.printStackTrace(); throw new Exception(""); } finally { try { if (os != null) { os.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (is != null) { is.close(); } } catch (Exception e) { } } } else { throw new Exception("源文件不存在或目標路徑不存在"); } }
列出文件夾下的所有文件
/** * 列出文件夾下的所有文件,使用遞歸。 <功能詳細描述> * * @param dirPath 文件夾絕對路徑 * @see [類、類#方法、類#成員] */ public static void getFileList(String dirPath) { File rootDir = new File(dirPath); if (rootDir.exists()) { File[] files = rootDir.listFiles(); for (File file : files) { if (file.isDirectory()) { System.out.println("目錄" + file.getName()); // 遞歸調用 getFileList(file.getPath()); } else { System.out.println("文件" + file.getName()); } } } }
