使用Java NIO将文件从一个目录移动到另一个目录

Gre*_*989 6 java directory io nio

我正在使用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
     }
}
Run Code Online (Sandbox Code Playgroud)

迭代以"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
}
Run Code Online (Sandbox Code Playgroud)

我得到了java.nio.file.FileAlreadyExistsException,因为我的文件夹(2014)已经存在.我真正想做的是将所有以"2014"开头的文件移到2014年目录中.

And*_*rew 11

最好不要回到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();
    }
Run Code Online (Sandbox Code Playgroud)


Stu*_*aie 10

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"
Run Code Online (Sandbox Code Playgroud)