實例如下所示:
public static void copyFolder(String srcFolder, String destFolder) throws IOException { long startTime = System.currentTimeMillis(); final Path srcPath = Paths.get(srcFolder); // 這裡多創建一級,就解決了沒有外殼的問題final Path destPath = Paths.get(destFolder, srcPath.toFile().getName()); // 檢查源文件夾是否存在if (Files.notExists(srcPath)) { System.err.println("源文件夾不存在"); System.exit(1); } // 如果目標目錄不存在,則創建if (Files.notExists(destPath)) { Files.createDirectories(destPath); }// 這裡是官方例子的開頭,可能是針對大文件處理設置的參數// Files.walkFileTree(srcPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS),// Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {}//簡化後的開頭Files.walkFileTree(srcPath, new SimpleFileVisitor<Path>() { // 官方還調用了專門的文件夾處理,這裡沒使用// public FileVisitResult preVisitDirectory(Path dir, // BasicFileAttributes attrs) throws IOException {return null;} @Override // 文件處理,將文件夾也一併處理,簡潔些public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path dest = destPath.resolve(srcPath.relativize(file)); // 如果說父路徑不存在,則創建if (Files.notExists(dest.getParent())) { Files.createDirectories(dest.getParent()); } Files.copy(file, dest); return FileVisitResult.CONTINUE; } }); long endTime = System.currentTimeMillis(); System.out.println("複製成功!耗時:" + (endTime - startTime) + "ms"); } // 刪除文件夾public static void deleteFolder(String Foleder) throws IOException { Path start = Paths.get(Foleder); if (Files.notExists(start)) { throw new IOException("文件夾不存在!"); } Files.walkFileTree(start, new SimpleFileVisitor<Path>() { @Override //構成了一個內部類// 處理文件public FileVisitResult visitFile(Path file,BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override // 再處理目錄public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { throw e; } } }); System.out.println("刪除成功!"); } public static void main(String[] args) throws IOException {//copyFolder("C://Users//Administrator//Desktop//111", "D://壓縮//1級//2級");// 419ms,378ms,429ms....deleteFolder("C://Users//Administrator//Desktop//111");}如有問題,還請提出,謝謝!
以上這篇JDK1.7 Paths,Files類實現文件夾的複制與刪除的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。