java nio copy,Java:使用nio Files.copy移动目录

I am new to the nio class, and am having trouble moving a directory of files to a newly created directory.

I first create 2 directories with:

File sourceDir = new File(sourceDirStr); //this directory already exists

File destDir = new File(destDirectoryStr); //this is a new directory

I then try to copy the existing files into the new directory, using:

Path destPath = destDir.toPath();

for (int i = 0; i < sourceSize; i++) {

Path sourcePath = sourceDir.listFiles()[i].toPath();

Files.copy(sourcePath, destPath.resolve(sourcePath.getFileName()));

}

This throws the following error:

Exception in thread "main" java.nio.file.FileSystemException: destDir/Experiment.log: Not a directory

I know that destDir/Experiment.log is not an existing directory; it should be a new file as a result of the Files.copy operation. Could someone point out where my operation is going wrong? Thanks!

解决方案

You need to use walkFileTree to copy directories. If you use Files.copy on a directory only an empty directory will be created.

File src = new File("c:\\temp\\srctest");

File dest = new File("c:\\temp\\desttest");

Path srcPath = src.toPath();

Path destPath = dest.toPath();

Files.walkFileTree(srcPath, new CopyDirVisitor(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING));

public static class CopyDirVisitor extends SimpleFileVisitor

{

private final Path fromPath;

private final Path toPath;

private final CopyOption copyOption;

public CopyDirVisitor(Path fromPath, Path toPath, CopyOption copyOption)

{

this.fromPath = fromPath;

this.toPath = toPath;

this.copyOption = copyOption;

}

@Override

public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException

{

Path targetPath = toPath.resolve(fromPath.relativize(dir));

if( !Files.exists(targetPath) )

{

Files.createDirectory(targetPath);

}

return FileVisitResult.CONTINUE;

}

@Override

public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException

{

Files.copy(file, toPath.resolve(fromPath.relativize(file)), copyOption);

return FileVisitResult.CONTINUE;

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值