2014-10-31 108 views
6

我是Java的nio軟件包的新手,我無法弄清楚如何將文件從一個目錄轉移到另一個目錄。我的程序應該讀取一個目錄及其子目錄和基於特定條件的進程文件。我可以使用Files.walkFileTree獲取所有文件,但是當我嘗試移動它們時,我得到一個java.nio.file.AccessDeniedException。如何將文件移動到非空目錄?

如果我嘗試複製它們,我得到一個DirectoryNotEmptyException。我一直無法在Google上找到任何幫助。我確定必須有一種簡單的方法將文件從一個目錄移動到另一個目錄,但我無法弄清楚。

這就是我想要的是得到DirectoryNotEmptyException:

private static void findMatchingPdf(Path file, ArrayList cgbaFiles) { 
    Iterator iter = cgbaFiles.iterator(); 
    String pdfOfFile = file.getFileName().toString().substring(0, file.getFileName().toString().length() - 5) + ".pdf"; 
    while (iter.hasNext()){ 
     Path cgbaFile = (Path) iter.next(); 
     if (cgbaFile.getFileName().toString().equals(pdfOfFile)) { 
      try { 
       Files.move(file, cgbaFile.getParent(), StandardCopyOption.REPLACE_EXISTING); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 
    } 
} 

我通過遍歷文件列表,試圖匹配具有相同名稱的.PDF一個.META文件。一旦找到匹配項,我將元數據文件移至具有pdf的目錄。

我得到這個異常: java.nio.file.DirectoryNotEmptyException:C:\測試\ CGBA-RAC \組分A 在sun.nio.fs.WindowsFileCopy.move(WindowsFileCopy.java:372) 在sun.nio.fs.WindowsFileSystemProvider.move(WindowsFileSystemProvider.java:287) at java.nio.file.Files.move(Files.java:1347) at cgba.rac.errorprocessor.ErrorProcessor.findMatchingPdf(ErrorProcessor.java: 149) 在cgba.rac.errorprocessor.ErrorProcessor.matchErrorFile(ErrorProcessor.java:81) 在cgba.rac.errorprocessor.ErrorProcessor.main(ErrorProcessor.java:36)

+0

我編輯的一些代碼在我的任擇議定書。 – user2406854 2014-10-31 16:31:35

+0

可能的重複[如何將文件複製到Java 7中的目錄](http://stackoverflow.com/questions/19694471/how-to-copy-a-file-to-a-directory-in-java- 7) – naXa 2015-08-27 14:34:27

回答

11
Files.move(file, cgbaFile.getParent(), StandardCopyOption.REPLACE_EXISTING); 

爲目標,你提供你想要的文件移動到該目錄中。這是不正確的。目標應該是您希望文件具有的新路徑名 - 新目錄加上文件名。

例如,假設您想將/tmp/foo.txt移動到/var/tmp目錄。當您應該撥打Files.move("/tmp/foo.txt", "/var/tmp/foo.txt")時,您打電話給Files.move("/tmp/foo.txt", "/var/tmp")

由於JVM試圖刪除目標目錄以便將其替換爲該文件,您正在獲取該特定錯誤。

其中一個應該生成正確的目標路徑:

Path target = cgbaFile.resolveSibling(file.getFileName()); 

Path target = cgbaFile.getParent().resolve(file.getFileName()); 
+0

謝謝,這是迄今爲止我見過的最清晰的解釋。 – user2406854 2014-10-31 19:57:15

3
Path source = Paths.get("Var"); 
Path target = Paths.get("Fot", "Var"); 
try { 
    Files.move(
     source, 
     target, 
     StandardCopyOption.REPLACE_EXISTING); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

java.nio.file.Files是必需的,所以這裏是編輯的解決方案。請看看它是否工作怎麼我從來沒有使用過的新文件課前

相關問題