複製文件工具類工具
/* * 複製一個文件的封裝方法 */ public static void copyOneFileTo(File fileSource, File fileAim) { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(new FileInputStream(fileSource)); bos = new BufferedOutputStream(new FileOutputStream(fileAim)); byte[] b = new byte[1024 * 8]; int n; while ((n = bis.read(b)) != -1) { bos.write(b); bos.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
2. 利用遞歸遍歷將所要複製的目錄下的文件都遍歷出來,而後調用複製單一文件的方法將目錄下的非文件夾文件複製到目標路徑。
/* * 遞歸遍歷了文件,並複製 */ public static void copyFile(File fileInTo, File fileOutTo) { File[] listFiles = fileInTo.listFiles(); for (File file : listFiles) { if (file.isDirectory()) { File file2 = new File(fileOutTo.getAbsolutePath() + "/" + file.getName()); file2.mkdirs(); copyFile(file, file2); } else { copyOneFileTo(file, new File(fileOutTo.getAbsolutePath() + "/" + file.getName())); } } }