Check if file exists without creating it

后端 未结 4 1896
花落未央
花落未央 2020-12-03 05:05

If I do this:

File f = new File(\"c:\\\\text.txt\");

if (f.exists()) {
    System.out.println(\"File exists\");
} else {
    System.out.println(\"File not f         


        
4条回答
  •  情深已故
    2020-12-03 05:28

    Starting from Java 7 you can use java.nio.file.Files.exists:

    Path p = Paths.get("C:\\Users\\first.last");
    boolean exists = Files.exists(p);
    boolean notExists = Files.notExists(p);
    
    if (exists) {
        System.out.println("File exists!");
    } else if (notExists) {
        System.out.println("File doesn't exist!");
    } else {
        System.out.println("File's status is unknown!");
    }
    

    In the Oracle tutorial you can find some details about this:

    The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists, or does not exist. You can do so with the exists(Path, LinkOption...) and the notExists(Path, LinkOption...) methods. Note that !Files.exists(path) is not equivalent to Files.notExists(path). When you are testing a file's existence, three results are possible:

    • The file is verified to exist.
    • The file is verified to not exist.
    • The file's status is unknown. This result can occur when the program does not have access to the file.

    If both exists and notExists return false, the existence of the file cannot be verified.

提交回复
热议问题