0

所以我尝试在我的 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.");
    }
4

1 回答 1

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);
    }
}
于 2015-07-10T13:47:17.643 回答