使用Java NIO将文件从一个目录移动到另一个目录 [英] Moving files from one directory to another with Java NIO

查看:273
本文介绍了使用Java NIO将文件从一个目录移动到另一个目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NIO库,但是当我尝试将文件从一个目录移动到另一个目录时,我会收到一个奇怪的错误。

I am using the NIO libraries but I am getting a strange error when I try to move files from one directory to another.

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)

Iterate over elements that start with "2014" and move them in the new directory (newDir, which is also called 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目录。

I get the java.nio.file.FileAlreadyExistsException because my folder (2014) already exists. What I actually want to do is move all the files that start with "2014" INSIDE the 2014 directory.

推荐答案

Files.move 不等同于 mv 命令。它不会检测到目的地是目录并将文件移动到那里。

Files.move is not equivalent to the mv command. It won't detect that the destination is a directory and move files into there.

您必须逐个文件构建完整的目标路径。如果要将 /src/a.txt 复制到 / dest / 2014 / ,目标路径需要

You have to construct the full destination path, file by file. If you want to copy /src/a.txt to /dest/2014/, the destination path needs to be /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"

这篇关于使用Java NIO将文件从一个目录移动到另一个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆