Check if file exists

This example will demonstrate how to check if a file already exist in the file system using straight up java and java 7 file api. In the instance you are running a batch process where you want to check to see if the file exists before appending or continue a process the snippets below will show how to do this.

Straight up Java

Using File and passing a location we will call the exists method which will return true if the file or directory denoted by this abstract pathname exists.

File exists

public void check_if_file_exists_java () {

    File file = new File("/");

    if (file.exists()) {"File existed");
    } else {"File not found");

Java 7 File I/O

Similar to above we will test if the file exists by using the Files.exists method. One difference is we can specify an options parameter which can be used to indicate if you want to follow symbolic links. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

public void check_if_file_exist_java_files () {

    Path filePath = Paths.get("/");

    boolean fileExists = Files.exists(filePath, LinkOption.NOFOLLOW_LINKS);