java nio拷贝目录,使用Java 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 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

}

}

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

}

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 is not equivalent to the mv command. It won't detect that the destination is a directory and move files into there.

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.

You may want to do something like this:

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"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值