Check if a File Exists

JavaJavaBeginner
Practice Now

Introduction

In Java programming, developers often need to check if a file or directory exists at a specified location or path. The exists() method of File class in Java can be used to check the presence of the specified file or directory. In this lab, we will take a step-by-step approach to demonstrate the code to check the existence of a file using Java programming.

Create a Java file

Create a Java file named FileExists.java in the ~/project directory using the following command:

touch ~/project/FileExists.java

Import required packages

In the newly created FileExists.java file, import the required packages as follows:

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

The java.io.File package is used to represent files and directories whereas java.io.IOException package is used for input-output operations.

Define the main() method

Create the main method as follows:

public static void main(String[] args) throws IOException{
    //code to check whether the file exists or not
}

Here, we declare the main() method which is the starting point of the program.

Define the file path

Create a file object by specifying the path of the file including its file name (e.g. example.txt) as follows:

File file = new File("/path/to/file/example.txt");

This code creates a File object named file and the path to the file is "/path/to/file/example.txt". Replace this path with the desired file path.

Check if the file exists

Using the exists() method, check whether the specified file exists or not as shown below:

boolean fileExists = file.exists();
if(fileExists){
    System.out.println("File exists");
}

This code checks for the existence of the file and if it exists, it will print out "File Exists". Otherwise, it will not print anything.

Check if the file is a directory or a file

Add the following code to check if the existing file is a file or a directory:

boolean isFile = file.isFile();
if(!isFile){
    System.out.println("It is not a file");
}else{
    System.out.println("It is a file");
}

This code checks if the existing file is a file or a directory. If it is a directory, it will print out "It is not a file". Otherwise, it will print out "It is a file".

Compile and run the program

Compile the program as follows:

javac ~/project/FileExists.java

Once the code is compiled successfully, run the program using the following command:

java ~/project/FileExists

Summary

In this lab, we have outlined a step-by-step approach to demonstrate how to check whether the file exists or not in Java programming. We used the File class in Java API which has the exists() method to test the file or directory presence. The isFile() method is also used to check if the file is a file or a directory.

Other Java Tutorials you may like