Checking the file entity is critical especially when the application deals with the file management tasks or stores the user data in specific directories. It must be ensured that the selected path leads to our desired file or directory which already exists. In case, the data is sent to a random file without ensuring its nature and existence, there are high chances of the loss of that sent data.
This guide explains the procedure to check if a file or directory exists or not in Java.
How to Check If a File or Directory Exists in Java?
There are a couple of ways to check, if the provided path of a file or directory exists or not. The provided path can be absolute or relative according to the requirements. These file paths can either be found manually using “File Explorer” or by the utilization of specific predefined methods. There are basically three types of file or directory paths which are mostly used, these path types are stated below:
- The “Relative” path is the shortest path and it is used to increase the flexibility and movement of the targeted file or directory. If the provided path is relative then only part of the whole path needs to be modified according to the updated location. It is retrieved in Java by invoking the “getPath()” method.
- The “Absolute” path is most popularly used when the project files or directory location will not be changed in the future. This path contains the whole address of the file from the Windows drive. The path can be retrieved by the utilization of a “getAbsolutePath()” method.
- The “Canonical” path looks similar to the “absolute” path as it also contains the full path of a file from the Windows drive. It is retrieved by invoking the “getCanonicalPath()” method.
For a better differentiation between the above-discussed path types, visit the below code block:
import java.io.File;
import java.io.IOException;
public class javabeat {
//initializing the main() method
public static void main(String[] args) throws IOException{
File targetedFile = new File("assets/index/hello.java/");
String absPath = targetedFile.getAbsolutePath();
System.out.println("\nThe Absolute Path Appears like this:\n\t " + absPath);
String canonicalPath = targetedFile.getCanonicalPath();
System.out.println("The Canonical Path looks like this:\n\t " + canonicalPath);
String relativePath = targetedFile.getPath();
System.out.println("The Relative Path will be:\n\t " + relativePath);
}
}
The explanation of the above code snippet is shown below:
- First, import the required “File” and “IOException” java utilities. Create a class containing the “main()” method that throws “IOException” to handle tasks related to input and output operations.
- Next, create an instance “targetedFile” for the “File” class and pass the file or directory path as its parameter.
- Now, apply the “getAbsolutePath()” method on the “targetedFile” instance. Store the result in the “absPath” variable, and display it on the console. The “absPath” contains the retrieved absolute path for the provided file path.
- In the same manner, apply the “getCanonicalPath()” and “getPath()” methods with the “targetedFile” instance to retrieve the Canonical and Relative path of a file or directory.
The generated output displays the retrieved paths:
After getting an idea about file or directory paths and how the user can generate them. Let’s dive into the methods to check if a file or directory exists at the provided path or not.
Method 1: Check If a File or Directory Exists Using a Legacy File.exists() Method
The “File.exists()” method is provided by a legacy “java.io.File” utility and the file path that is going to be checked is stored inside the “File” class instance. This method does not create any difference between file and folder. That’s why it returns true if the provided path leads to the existence of a file or folder. The implementation of “File.exists()” method is shown below:
import java.io.File;
import java.io.IOException;
public class javabeat {
public static void main(String[] args) throws IOException{
File asset = new File("assets/demo.java/");
if (asset.exists())
System.out.println("File or Directory Exists");
else
System.out.println("File or Directory does not Exist at provided path");
}
}
The description of the above code snippet is shown below:
- First, import the “File” and “IOException” java utilities. Create a class containing the “main()” method that throws “IOException” to handle tasks related to input and output operations.
- Next, create an instance of the “File” class and pass the selected path as a parameter for the class constructor.
- Then, apply the “exists()” method with the “asset” File instance and pass the whole operation in the “if” statement that displays a message according to the found result.
The generated output for the above code snippet confirms the existence of the selected file or directory:
Method 2: Check If a File or Directory Exists Using “java.nio.file” Files.exists() and Files.notExists() Methods
The “java.nio.file” java utility provides “Files” and “Paths” classes to perform several file-related operations like checking their existence. The “Paths” class creates an instance containing the targeted file path that is passed to the “exists()” and “notExists()” methods. To check if a file or directory exists at the provided path or not. For instance, take a look at the below code snippet:
import java.nio.file.*;
import java.io.IOException;
public class javabeat {
public static void main(String[] args) throws IOException{
Path = Paths.get("assets/");
System.out.println("Using Exists() Method");
if (Files.exists(path))
{
System.out.println("\tFile or Directory Exists");
}
else
{
System.out.println("\tFile or Directory does not Exist at provided path");
}
System.out.println("\nUsing notExists() Method");
Path secondPath = Paths.get("assets/demo.java");
if (Files.notExists(secondPath))
{
System.out.println("\tFile or Directory not found");
}else
{
System.out.println("\tFile or Directory is found");
}
}
}
The above code works like this:
- First, import the “java.nio.file” and “java.io.IOException” to utilize the “Files” and “Paths” classes.
- Next, create an instance named “path” of the class “Paths” and apply the “if” statement. Inside the “if” condition pass the “path” as an argument for the “Files.exists()” method.
- The success or failure message will be displayed on the console according to the existence of the specified file or directory.
- Now, create another path using the same “Paths.get()” method and pass the retrieved path as the parameter for the “Files.notExists()” method.
- After that, display the success or failure messages according to the result provided by the “notExists()” method.
The generated output shows that our desired file exists and it is checked for both methods:
Bonus Tip: Check If the Path Leads to an Existing file or Directory
The methods provided by the “java.io.File” and “java.nio.file.Files” utilities can be used to identify whether the provided path leads to a file or directory. The methods provided by “java.io.File” are “isFile”, “isDirectory()”, and “canRead()”. In the case of the “java.nio.file.Files” utility, the methods are “isRegularFile()”, “isDirectory()” and “canRead()”. The practical implementation of these methods is stated below:
import java.nio.file.*;
import java.io.File;
import java.io.IOException;
public class javabeat {
public static void main(String[] args) throws IOException{
Path = Paths.get("assets/");
System.out.println("Using Files Class Method");
if (Files.isDirectory(path))
{
System.out.println("\tProvided Path Leads to a File");
}
else if (Files.isRegularFile(path))
{
System.out.println("\tProvided Path Leads to a Directory");
}
else
{
System.out.println("\tFile or Directory does not Exist at provided path");
}
if (Files.isReadable(path))
{
System.out.println("\tFile Residing at provided Path is Readable");
}
System.out.println("\nUsing File Class Method");
File secondPath = new File("assets/demo.java");
if (secondPath.isDirectory())
{
System.out.println("\tProvided Path Leads to a File");
}
if (secondPath.isFile() )
{
System.out.println("\tProvided Path Leads to a Directory");
}
if (secondPath.canRead())
{
System.out.println("\tFile Residing at provided Path is Readable");
}
else
{
System.out.println("\tFile or Directory does not Exist at provided path");
}
}
}
The above code works like this:
- Start by importing the required modules namely “java.nio.file.Files”, “java.nio.file.*”, “java.io.File”, and “java.io.IOException”.
- Next, inside the “main()” method creates a new instance of the “Paths” class containing the targeted file path which is going to be checked.
- The created path instance is then passed as an argument into the “Files.isDirectory()”, “Files.isRegularFile()”, and “Files.canRead()” methods. These methods tell if the provided path leads to a file, directory, and its readability, respectively.
- After that, the instance of a “File” class is created, namely “secondPath”. The provided path which is required to be checked is passed as an argument in the File class constructor.
- Next, the “isDirectory()”, “isFile()”, and “canRead()” methods are applied to the “secondPath” variable.
- These methods tell whether the provided path is a “file”, “directory”, or “readable” by displaying corresponding messages on the console.
The generated output shows that the type of asset led by the provided path has been checked along with its readability factor:
Conclusion
To check if a file or directory exists in Java, use the “exists()” method provided by two utilities “java.nio.file.Files” or “java.io.File”. In the case of “java.nio.file.Files”, the path is passed as a parameter in the constructor of the “Path” class which is then passed to the “exists()” method. For “java.io.file”, the provided path is stored in the “File” type instance and the “exists()” method is directly applied to that instance. This guide has explained the approaches that can be used to check if a file or directory exists in Java.