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.
To check if file exists in Java we can use
exists() method available on
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.
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.
The above example will provide the following result:
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.