2014-03-12 165 views
3

我正在使用NIO庫,但是當我嘗試將文件從一個目錄移動到另一個目錄時出現奇怪的錯誤。使用Java NIO將文件從一個目錄移動到另一個目錄

String yearNow = new SimpleDateFormat("yyyy").format(
    Calendar.getInstance().getTime()); 

try { 
    DirectoryStream<Path> curYearStream = 
     Files.newDirectoryStream(sourceDir, "{" + yearNow + "*}"); 
     //Glob for current year 

    Path newDir = Paths.get(sourceDir + "//" + yearNow); 

    if (!Files.exists(newDir) || !Files.isDirectory(newDir)) { 
     Files.createDirectory(newDir); 
     //create 2014 directory if it doesn't exist 
    } 
} 

遍歷與「2014」開始,在新的目錄(NEWDIR,也稱爲2014)移動這些元素

for (Path p : curYearStream) { 
    System.out.println(p); //it prints out exactly the files that I need to move 
    Files.move(p, newDir); //java.nio.file.FileAlreadyExistsException 
} 

我得到的java.nio.file.FileAlreadyExistsException因爲我的文件夾(2014)已經存在。我真正想要做的是移動所有以「2014」爲開頭的文件在2014目錄中。

回答

8

Files.move不等於mv命令。它不會檢測到目標是一個目錄並將文件移動到那裏。

您必須構建完整的目標路徑,逐個文件。如果要將/src/a.txt複製到/dest/2014/,則目標路徑需要爲/dest/2014/a.txt

您可能需要做這樣的事情:

File srcFile = new File("/src/a.txt"); 
File destDir = new File("/dest/2014"); 
Path src = srcFile.toPath(); 
Path dest = new File(destDir, srcFile.getName()).toPath(); // "/dest/2014/a.txt" 
4

最好不要回去java.io.File的使用NIO來代替:

Path sourceDir = Paths.get("c:\\source"); 
    Path destinationDir = Paths.get("c:\\dest"); 

    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDir)) { 
     for (Path path : directoryStream) { 
      System.out.println("copying " + path.toString()); 
      Path d2 = destinationDir.resolve(path.getFileName()); 
      System.out.println("destination File=" + d2); 
      Files.move(path, d2, REPLACE_EXISTING); 
     } 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
0

使用java.io.File,它的這樣簡單:

File srcFile = new File(srcDir, fileName); 
srcFile.renameTo(new File(destDir, "a.txt")); 
相關問題