Search code examples
javanioexists

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


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?


Solution

  • 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();
            }