In Java, we can use Files.exists(path) to test whether a file exists. The path can be a file or a directory. It is better to combine with !Files.isDirectory(path) to ensure the existing file is not a directory.

  Path path = Paths.get("/home/favtuts/test/test.log");

  // file exists and it is not a directory
  if(Files.exists(path) && !Files.isDirectory(path)) {
      System.out.println("File exists!");
  }

1. Files.exists(path) (NIO)

This example uses Files.exists(path) to test whether a file exists.

FileExist.java

package com.favtuts.io.file;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileExist {

    public static void main(String[] args) {
        
        Path path = Paths.get("/home/tvt/workspace/favtuts/test/test.log");

        // check exists for file and directory
        if (Files.exists(path)) {

            if (Files.isRegularFile(path)) {
                System.out.println("File exists!");
            }

            if (Files.isDirectory(path)) {
                System.out.println("File exists, but it is a directory.");
            }

        } else {
            System.out.println("File doesn't exist");
        }
    }
    
}

1.2 If the file is a symbolic link or soft link, the Files.exists will follow the link by default. The Files.exists takes two arguments, we can pass a second LinkOption.NOFOLLOW_LINKS argument to tell the method stop to follow the symbolic link.

import java.nio.file.Files;
import java.nio.file.LinkOption;

    // do not follow symbolic link
    if(Files.exists(path, LinkOption.NOFOLLOW_LINKS)){
      //...
    }

1.3 There is a Files.notExists() to test the non-exists file.

  if(Files.notExists(path)){
      System.out.println("File doesn't exist");
  }

2. File.exists (Legacy IO)

The legacy IO java.io.File has a similar File.exists() to test whether a file or directory exists, but it has no support for symbolic links.

FileExist2.java

package com.favtuts.io.file;

import java.io.File;

public class FileExist2 {

    public static void main(String[] args) {

        File file = new File("/home/favtuts/test/");

        if(file.exists() && !file.isDirectory()){
            System.out.println("File exists!");
        }else{
            System.out.println("File doesn't exist");
        }

    }

}

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-io/file

References

Leave a Reply

Your email address will not be published. Required fields are marked *