【问题标题】:Why can't Java find this file in System32?为什么 Java 在 System32 中找不到这个文件?
【发布时间】:2015-07-09 18:17:24
【问题描述】:

所以我尝试在我的 System32 文件夹中删除一个文件夹,但 java 似乎找不到它...

    File gwxFolder = new File("C:/Windows/System32/GWX");

    System.out.println(gwxFolder.getPath());
    if(gwxFolder.exists()){
        IO.deleteFolder(gwxFolder);
    } else {
        JOptionPane.showMessageDialog(null, "Can't find your folder.");
    }

【问题讨论】:

  • 文件夹真的存在吗?
  • 您可能在 64 位系统上运行它。您还需要签入C:\Windows\SysWOW64
  • 我手动创建了那个文件夹,所以我 100% 确定它存在
  • 您遇到的错误是什么?您如何运行 Java 应用程序?文件夹的权限是什么?
  • 我没有收到任何错误,我只是收到了我的 MessageBox(“找不到您的文件夹”)。我从 Eclipse 运行它。我刚刚用另一个文件夹对其进行了测试,它运行良好。

标签: java io system32


【解决方案1】:

虽然我不能准确地告诉你出了什么问题,但我或许可以告诉你如何得到答案。

java.io.File 已过时。它是 Java 1.0 的一部分,由于各种原因,它的许多方法都不可靠,通常返回一个无意义的魔法值,如 0 或 null,而不是抛出一个实际描述故障性质的异常。

File 类已替换为Path。您可以通过Paths.getFile.toPath 获取Path 实例。

一旦你有了一个路径,对它的大多数操作都是用Files 类执行的。特别是,您可能想要Files.existsFiles.isDirectory

您可能还想考虑自己删除该目录,使用Files.walkFileTree,因此如果失败,您将获得一个有用且信息丰富的异常:

Path gwxFolder = Paths.get("C:\\Windows\\System32\\GWX");

if (Files.exists(gwxFolder)) {
    try {
        Files.walkFileTree(gwxFolder, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file,
                                             BasicFileAtttributes attributes)
            throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir,
                                                      IOException e)
            throws IOException {
                if (e == null) {
                    Files.delete(dir);
                }
                return super.postVisitDirectory(dir, e);
            }
        });
    } catch (IOException e) {
        StringWriter stackTrace = new StringWriter();
        e.printStackTrace(new PrintWriter(stackTrace, true));
        JOptionPane.showMessageDialog(null, stackTrace);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-05
    • 2011-08-03
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多