英文:
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();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论