Java IO - Check If File Exist

May 16, 2020 No comments Java IO FIle Exist

1. Introduction

In this article, we will present several methods to check if a file or directory exists in the filesystem. Java provides dedicated methods not only to list, create, delete or append content to the file but also to check if a specific file exists on the specific path.

This article is a part of the Java IO Tutorial.

2. Using File.exists() method

To check if file exists in Java we can use exists() method available on java.io.File class:

package com.frontbackend.java.io.exists;

import java.io.File;
import java.io.IOException;

public class CheckIfFileExistsUsingFileExistsMethod {

    public static void main(String[] args) {
        File temp;
        try {
            temp = File.createTempFile("frontbackend", ".txt");

            boolean exists = temp.exists();

            System.out.println("File exists: " + exists);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The result:

File exists: true

In the above example first, we created temp file frontbackend.txt on the tmp directory. Then we use temp.exists() a method that will determine if the file exists, in our case, it will check if the file was created successfully.

3. Using Files.exists() method

In the new IO package Java provides a method Files.exists() that can be used to check if resources under specified path exists in the filesystem.


package com.frontbackend.java.io.exists;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CheckIfFileExistsUsingFilesExistsMethod {

    public static void main(String[] args) throws IOException {
        final Path path = Files.createTempFile("frontbackend", ".txt");

        System.out.println("File exists : " + Files.exists(path)); // true
        System.out.println("File not exists: " + Files.notExists(path)); // false
    }
}

The above example will provide the following result:

File exists : true
File not exists: false

4. Conclusion

In this tutorial, we showcased two common methods to check if a file exists in Java. Operations of the filesystem are commonly used in many applications. Fortunately, Java pleased developers with a great set of methods for file manipulation.

As usual, the code used in this article can be found in our GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}