java基於遞迴思想的檔案拷貝
阿新 • • 發佈:2019-01-30
這段程式碼原本目的是掃描是否插入U盤,插入的話,自動將U盤檔案全部備份到目標資料夾中。
檔案目錄是樹狀結構,很有層次感,且每層操作大致相同。複製目錄中的檔案,不是建立資料夾操作,就是複製檔案操作,所以遞迴思想在這裡很適用。
程式碼如下:
/**** * * @author wjw * @since 2018-02-27 * */ public class Copy { public static void main(String[] args) throws IOException, InterruptedException { // 配置檔案配置輪詢碟符 int second = 10;// 輪詢檔案是否存在時間間隔 String souPath = "H:/"; // 源路徑 String desPath = "E:/U/test"; // 目標路徑 File file = new File(souPath); while (!file.exists()) { System.out.println(souPath + "目錄不存在!"); Thread.sleep(1000 * second); } long beginMillis = System.currentTimeMillis(); copy(souPath, desPath); System.out.println("複製檔案約耗時: " + (System.currentTimeMillis() - beginMillis) / 1000 + " s."); } public static void copy(String souPath, String desPath) throws IOException { File dir = new File(souPath); if (dir.isDirectory()) { System.out.println("開始拷貝目錄 " + souPath + " 中的檔案到目錄 " + desPath + " 中..."); String[] filesStr = dir.list(); for (int i = 0; i < filesStr.length; i++) { String tempSouPath = souPath + File.separator + filesStr[i]; String tempDesPath = desPath + File.separator + filesStr[i]; if (new File(tempSouPath).isDirectory()) { createDir(tempDesPath); copy(tempSouPath, tempDesPath); } else { copyFile(tempSouPath, tempDesPath); } } System.out.println(souPath + "目錄中的檔案拷貝完畢!"); } else if (dir.isFile()) { copyFile(souPath, desPath); } } /**** * 建立目錄 * * @param dirPath */ public static void createDir(String dirPath) { // System.out.println("建立目錄:" + dirPath); File file = new File(dirPath); if (file != null) { if (!file.exists()) { file.mkdir(); } } } /******* * 複製檔案 * * @throws IOException */ public static void copyFile(String sourcePath, String desPath) throws IOException { System.out.println(" 開始拷貝檔案 " + sourcePath + "..."); FileInputStream fis = null; FileOutputStream fos = null; File file = new File(sourcePath); if (file != null && file.isFile()) { fis = new FileInputStream(file); File des = new File(desPath); fos = new FileOutputStream(des); int bufferSize = 1024; byte[] data = new byte[bufferSize]; int length = 0; while ((length = fis.read(data, 0, bufferSize)) != -1) { fos.write(data, 0, length); } } fis.close(); fos.close(); System.out.println(" " + desPath + "檔案拷貝完畢!"); } }
如有錯誤,歡迎指正!
end