【问题标题】:How can I move a file to a non-empty directory?如何将文件移动到非空目录?
【发布时间】:2014-10-31 15:46:39
【问题描述】:

我是 Java 的 nio 包的新手,我不知道如何将文件从一个目录获取到另一个目录。我的程序应该根据某些条件读取目录及其子目录并处理文件。我可以使用 Files.walkFileTree 获取所有文件,但是当我尝试移动它们时,我得到一个 java.nio.file.AccessDeniedException。

如果我尝试复制它们,我会收到 DirectoryNotEmptyException。我无法在 Google 上找到任何帮助。我确信必须有一种简单的方法将文件从一个目录移动到另一个目录,但我不知道。

这就是我正在尝试获取 DirectoryNotEmptyException:

private static void findMatchingPdf(Path file, ArrayList cgbaFiles) {
    Iterator iter = cgbaFiles.iterator();
    String pdfOfFile = file.getFileName().toString().substring(0, file.getFileName().toString().length() - 5) + ".pdf";
    while (iter.hasNext()){
        Path cgbaFile = (Path) iter.next();
        if (cgbaFile.getFileName().toString().equals(pdfOfFile)) {
            try {
                Files.move(file, cgbaFile.getParent(), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

我正在遍历文件列表,试图将 .meta 文件与同名的 .pdf 文件进行匹配。找到匹配项后,我将元数据文件移动到包含 pdf 的目录。

我得到了这个例外: java.nio.file.DirectoryNotEmptyException: C:\test\CGBA-RAC\Part-A 在 sun.nio.fs.WindowsFileCopy.move(WindowsFileCopy.java:372) 在 sun.nio.fs.WindowsFileSystemProvider.move(WindowsFileSystemProvider.java:287) 在 java.nio.file.Files.move(Files.java:1347) 在 cgba.rac.errorprocessor.ErrorProcessor.findMatchingPdf(ErrorProcessor.java:149) 在 cgba.rac.errorprocessor.ErrorProcessor.matchErrorFile(ErrorProcessor.java:81) 在 cgba.rac.errorprocessor.ErrorProcessor.main(ErrorProcessor.java:36)

【问题讨论】:

标签: java nio


【解决方案1】:
Files.move(file, cgbaFile.getParent(), StandardCopyOption.REPLACE_EXISTING);

对于目标,您提供了要将文件移动到的目录。这是不正确的。目标应该是您希望文件具有的新路径名——新目录加上文件名。

例如,假设您想将/tmp/foo.txt 移动到/var/tmp 目录。当你应该打电话给Files.move("/tmp/foo.txt", "/var/tmp/foo.txt")时,你打电话给Files.move("/tmp/foo.txt", "/var/tmp")

您收到该特定错误是因为 JVM 正在尝试删除目标目录以将其替换为文件。

其中一个应该生成正确的目标路径:

Path target = cgbaFile.resolveSibling(file.getFileName());

Path target = cgbaFile.getParent().resolve(file.getFileName());

【讨论】:

  • 谢谢,这是迄今为止我看到的最清晰的解释。
【解决方案2】:
Path source = Paths.get("Var");
Path target = Paths.get("Fot", "Var");
try {
    Files.move(
        source,
        target,  
        StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}

java.nio.file.Files 是必需的,所以这里是编辑的解决方案。请看看它是否有效,因为我以前从未使用过新的 Files 类

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 2017-10-09
    相关资源
    最近更新 更多