如何在Java中复制zip文件

时间:2014-09-26 18:20:16

标签: java

我有一个在运行时创建的zip文件,我需要将其复制到另一个目录,但每当我运行我的代码时,我都会得到一个DirectoryNotEmptyException。是否需要指定一些额外的参数来复制到非空目录中?

这是布局

Path sourceZip = new File(path).toPath();
String destinDir = new File(System.getProperty("user.dir")).getParent();
Path target = Paths.get(destinDir);
try {
       Files.copy(sourceZip, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) //DirectoryNotEmptyException occurs here
{}

1 个答案:

答案 0 :(得分:0)

目标需要包含最终将存在的文件的完整路径。

所以你说如果你需要将/home/dauser/faq.txt复制到/home/faq.txt

File file = new File(path);
Path sourceZip = file.toPath();
StringBuilder sb = new StringBuilder();
sb.append(new File(System.getProperty("user.dir")).getParent());
sb.append("/");
sb.append(file.getName());
Path target = Paths.get(sb.toString());
try {
   Files.copy(sourceZip, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) //DirectoryNotEmptyException occurs here
{}