Files.exists() 在测试常规文件时返回 false,而在测试目录时返回 true。

huangapple go评论48阅读模式
英文:

Files.exists() returning false when a regular file is tested and true when a directory is tested

问题

我在当前工作目录(C)内创建了一个名为"examples"的目录,在其中创建了一个名为"test.txt"的.txt文件,但是当我使用Files.exists()测试该文件时,它返回false。

System.out.println(Files.exists(Path.of("\\examples\\test.txt")));

所以,我用一个同名的目录"test.txt"替换了文本文件"test.txt"。现在Files.exists()返回true。
这可能意味着路径是正确的,但我的常规文件出了问题。

为什么在这两种情况下exists()都没有返回true呢?

英文:

I created a directory called "examples" inside my current working directory (C) and inside it I created a .txt file called "test.txt", but when I test the file using Files.exists(), it returns false.

System.out.println(Files.exists(Path.of("\\examples\\test.txt")));

So, I replaced the text file "test.txt" with a directory with the same name, ie, "test.txt". Now Files.exists() returns true.
This might mean that the path is correct but something is wrong with my regular file.

why is'nt exists() returning true in both cases?

答案1

得分: 0

尝试按以下方式创建目录和文件:

try {
    Path examples = Paths.get("examples");
    if (Files.notExists(examples)) // 如果路径不存在
        Files.createDirectories(examples); // 创建为目录

    Path path = examples.resolve("test.txt"); // 解析文件
    if (Files.notExists(path)) // 如果不存在
        Files.createFile(path); // 创建文件

    System.out.println("path = " + path);
    System.out.println("Files.exists(path) = " + Files.exists(path));

} catch (IOException ex) {
    ex.printStackTrace();
}
英文:

Try to create a directory and a file as follows:

        try {
            Path examples = Paths.get("examples");
            if (Files.notExists(examples)) // if path not exists
                Files.createDirectories(examples); // create as directory

            Path path = examples.resolve("test.txt"); // resolve file
            if (Files.notExists(path)) // if not exists
                Files.createFile(path); // create file

            System.out.println("path = " + path);
            System.out.println("Files.exists(path) = " + Files.exists(path));

        } catch (IOException ex) {
            ex.printStackTrace();
        }

huangapple
  • 本文由 发表于 2023年2月16日 02:01:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75463762.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定