What method of the File class is used to check if a file is existing or not?

Java provides extensive support to File Handling. In other words, File handling in Java implies reading from and writing data to a file. The File class from the java.io package, allows us to work with different formats of files. But, before operating on file, we need to check if a file exists or not. There are three possibilities for the file either file exist, or file doesn’t exist or it may be possible that file status is not known.

In Java, there are three different ways to check if a file exists or not. They are as listed below.

Advertisement

  • Using exists method of Legacy I/O File class
  • Using isFile method of File class
  • Using exists method of NIO File class

 

Method-1: Using exists method of File class

Prior to the Java SE 7 release, the java.io.File class was the mechanism used for file I/O, but it had several drawbacks. The

// Importing File package
import java.io.File;
public class Main {
    public static void main(String[] args) {

        // Initializing string to store the path
        String s1 = "C:\\sample.txt";
        String s2 = "C:\\xyz.txt";

        // Creating file handle	
        File f1 = new File(s1);
        File f2 = new File(s2);

        // Check if file a exists and is not directory
        if (f1.exists() & amp; & amp; !f1.isDirectory()) {
            System.out.println(f1 + " exists in the given directory.");
        } else {
            System.out.println(f1 + " does not exists or it may be a directory.");
        }

        // Check if a file exists
        if (f2.exists()) {
            System.out.println(f2 + " exists in the given directory.");
        } else {
            System.out.println(f2 + " does not exists in the given directory.");
        }

    }
}
0 is a static method of java.io.File class that tests whether a file exist or not. This is a traditional approach to find if the file exists or not. This method does not accept any parameter. However, it returns a boolean value True or False to indicate if the file exist or not. Moreover, this method will raise a Security Exception if the file does not have a write access.

ALSO READ: How to initialize List in Java [Practical Examples]

There is one more issue with only using the

// Importing File package
import java.io.File;
public class Main {
    public static void main(String[] args) {

        // Initializing string to store the path
        String s1 = "C:\\sample.txt";
        String s2 = "C:\\xyz.txt";

        // Creating file handle	
        File f1 = new File(s1);
        File f2 = new File(s2);

        // Check if file a exists and is not directory
        if (f1.exists() & amp; & amp; !f1.isDirectory()) {
            System.out.println(f1 + " exists in the given directory.");
        } else {
            System.out.println(f1 + " does not exists or it may be a directory.");
        }

        // Check if a file exists
        if (f2.exists()) {
            System.out.println(f2 + " exists in the given directory.");
        } else {
            System.out.println(f2 + " does not exists in the given directory.");
        }

    }
}
0 method to check if a file exists or not. Because, it returns a true value if we accidentally specify a directory. So we have to use the method
// Importing File package
import java.io.File;
public class Main {
    public static void main(String[] args) {

        // Initializing string to store the path
        String s1 = "C:\\sample.txt";
        String s2 = "C:\\xyz.txt";

        // Creating file handle	
        File f1 = new File(s1);
        File f2 = new File(s2);

        // Check if file a exists and is not directory
        if (f1.exists() & amp; & amp; !f1.isDirectory()) {
            System.out.println(f1 + " exists in the given directory.");
        } else {
            System.out.println(f1 + " does not exists or it may be a directory.");
        }

        // Check if a file exists
        if (f2.exists()) {
            System.out.println(f2 + " exists in the given directory.");
        } else {
            System.out.println(f2 + " does not exists in the given directory.");
        }

    }
}
3 also to make sure that the given argument is a file but not a directory.

The syntax of exists method is as shown below.

	fileobject.exists()

 

Example : In this example, we will create two objects of file class that points to the file in the local directory. Here, we are using exists method of legacy file I/O class and is directory method to check if the given file is a directory or not.

// Importing File package
import java.io.File;
public class Main {
    public static void main(String[] args) {

        // Initializing string to store the path
        String s1 = "C:\\sample.txt";
        String s2 = "C:\\xyz.txt";

        // Creating file handle	
        File f1 = new File(s1);
        File f2 = new File(s2);

        // Check if file a exists and is not directory
        if (f1.exists() & amp; & amp; !f1.isDirectory()) {
            System.out.println(f1 + " exists in the given directory.");
        } else {
            System.out.println(f1 + " does not exists or it may be a directory.");
        }

        // Check if a file exists
        if (f2.exists()) {
            System.out.println(f2 + " exists in the given directory.");
        } else {
            System.out.println(f2 + " does not exists in the given directory.");
        }

    }
}

Output:

C:\sample.txt does not exists or it may be a directory.
C:\xyz.txt exists

 

ALSO READ: How to get Current Date in Java [Practical Examples]

Method-2: Using isFile method of File class

Prior to the Java SE 7 release, the

// Importing File package
import java.io.File;
public class Main {
    public static void main(String[] args) {

        // Initializing string to store the path
        String s1 = "C:\\sample.txt";
        String s2 = "C:\\xyz.txt";

        // Creating file handle	
        File f1 = new File(s1);
        File f2 = new File(s2);

        // Check if file a exists and is not directory
        if (f1.exists() & amp; & amp; !f1.isDirectory()) {
            System.out.println(f1 + " exists in the given directory.");
        } else {
            System.out.println(f1 + " does not exists or it may be a directory.");
        }

        // Check if a file exists
        if (f2.exists()) {
            System.out.println(f2 + " exists in the given directory.");
        } else {
            System.out.println(f2 + " does not exists in the given directory.");
        }

    }
}
4 is a static method of java.io.File class that tests whether a file exist or not. This is a also widely used approach to find if the file exists or not. This method does not accept any parameter. However, it returns a boolean value True or False to indicate if the file exist or not. Moreover, this method will raise a Security Exception if the file does not have a write access.

Advertisement

The advantage of using the

// Importing File package
import java.io.File;
public class Main {
    public static void main(String[] args) {

        // Initializing string to store the path
        String s1 = "C:\\sample.txt";
        String s2 = "C:\\xyz.txt";

        // Creating file handle	
        File f1 = new File(s1);
        File f2 = new File(s2);

        // Check if file a exists and is not directory
        if (f1.exists() & amp; & amp; !f1.isDirectory()) {
            System.out.println(f1 + " exists in the given directory.");
        } else {
            System.out.println(f1 + " does not exists or it may be a directory.");
        }

        // Check if a file exists
        if (f2.exists()) {
            System.out.println(f2 + " exists in the given directory.");
        } else {
            System.out.println(f2 + " does not exists in the given directory.");
        }

    }
}
4 method over the
// Importing File package
import java.io.File;
public class Main {
    public static void main(String[] args) {

        // Initializing string to store the path
        String s1 = "C:\\sample.txt";
        String s2 = "C:\\xyz.txt";

        // Creating file handle	
        File f1 = new File(s1);
        File f2 = new File(s2);

        // Check if file a exists and is not directory
        if (f1.exists() & amp; & amp; !f1.isDirectory()) {
            System.out.println(f1 + " exists in the given directory.");
        } else {
            System.out.println(f1 + " does not exists or it may be a directory.");
        }

        // Check if a file exists
        if (f2.exists()) {
            System.out.println(f2 + " exists in the given directory.");
        } else {
            System.out.println(f2 + " does not exists in the given directory.");
        }

    }
}
0 method is that we will not have to check if the given file is a directory or not. Unlike,
// Importing File package
import java.io.File;
public class Main {
    public static void main(String[] args) {

        // Initializing string to store the path
        String s1 = "C:\\sample.txt";
        String s2 = "C:\\xyz.txt";

        // Creating file handle	
        File f1 = new File(s1);
        File f2 = new File(s2);

        // Check if file a exists and is not directory
        if (f1.exists() & amp; & amp; !f1.isDirectory()) {
            System.out.println(f1 + " exists in the given directory.");
        } else {
            System.out.println(f1 + " does not exists or it may be a directory.");
        }

        // Check if a file exists
        if (f2.exists()) {
            System.out.println(f2 + " exists in the given directory.");
        } else {
            System.out.println(f2 + " does not exists in the given directory.");
        }

    }
}
0 method this file will not return True for directory.

The syntax of isFile method is as shown below.

	fileobject.isFile()

Example :

// Importing File package
import java.io.File;
class Main {
    public static void main(String[] args) {
        // Storing path as a string
        String p = "C:\pythondemo\test.txt";

        //Creating file object
        File f = new File(p);

        // Check if it is a file using isFile method
        if (f.isFile()) {
            System.out.println("The file " + p + " exists in the given directory.");
        } else {
            System.out.println("Either file " + p + " doesn't exist in the given directory or this program may not have access to the file");
        }
    }
}

Output:

Either file C:\pythondemo\test.txt doesn't exist in the given directory or this program may not have access to the file.

 

ALSO READ: How to Copy a File in Java [Practical Examples]

Method-3: Using NIO

From Java 7 onward, the

// Importing File package
import java.io.File;
public class Main {
    public static void main(String[] args) {

        // Initializing string to store the path
        String s1 = "C:\\sample.txt";
        String s2 = "C:\\xyz.txt";

        // Creating file handle	
        File f1 = new File(s1);
        File f2 = new File(s2);

        // Check if file a exists and is not directory
        if (f1.exists() & amp; & amp; !f1.isDirectory()) {
            System.out.println(f1 + " exists in the given directory.");
        } else {
            System.out.println(f1 + " does not exists or it may be a directory.");
        }

        // Check if a file exists
        if (f2.exists()) {
            System.out.println(f2 + " exists in the given directory.");
        } else {
            System.out.println(f2 + " does not exists in the given directory.");
        }

    }
}
0 method of java.nio.file.Files is a static method that returns true if the file exists. Whereas, the
C:\sample.txt does not exists or it may be a directory.
C:\xyz.txt exists
0 method returns true when it does not exist. Moreover, if both
// Importing File package
import java.io.File;
public class Main {
    public static void main(String[] args) {

        // Initializing string to store the path
        String s1 = "C:\\sample.txt";
        String s2 = "C:\\xyz.txt";

        // Creating file handle	
        File f1 = new File(s1);
        File f2 = new File(s2);

        // Check if file a exists and is not directory
        if (f1.exists() & amp; & amp; !f1.isDirectory()) {
            System.out.println(f1 + " exists in the given directory.");
        } else {
            System.out.println(f1 + " does not exists or it may be a directory.");
        }

        // Check if a file exists
        if (f2.exists()) {
            System.out.println(f2 + " exists in the given directory.");
        } else {
            System.out.println(f2 + " does not exists in the given directory.");
        }

    }
}
0 and
C:\sample.txt does not exists or it may be a directory.
C:\xyz.txt exists
0 return
C:\sample.txt does not exists or it may be a directory.
C:\xyz.txt exists
3, the existence of the file cannot be verified. This may happen when the program does not have access to the file. Also the result of this method is immediately outdated. So, if this method indicates the file exists then there is no guarantee that a sub sequence access will succeed. Thus, we must be careful when using this method in security sensitive applications.

Note that

C:\sample.txt does not exists or it may be a directory.
C:\xyz.txt exists
4 returns true when your path points to a directory. So, it is recommended to use this method along with the
C:\sample.txt does not exists or it may be a directory.
C:\xyz.txt exists
5 method, which checks the file for a directory.

Advertisement

The syntax of exists method and notExists method is as shown below.

Files.exists(path, options)
Files.notExists(path, options)

The options parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

Example : In this example, we are using get method to obtain a Path to the intended file or directory. Then we can pass that Path to the

C:\sample.txt does not exists or it may be a directory.
C:\xyz.txt exists
4 method.

// Importing File package
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
    public static void main(String[] args) {
        Path p = Paths.get("/sample.txt");

        // check if a file exists for file and directory
        if (Files.exists(p)) {
            // Check if it is a file
            if (Files.isRegularFile(p)) {
                System.out.println("File " + p + " exists in this directory!");
            }

            // Check if it is a directory
            if (Files.isDirectory(p)) {
                System.out.println("File " + p + " exists in this directory but, it is not a file. It is a directory.");
            }
        } else {
            System.out.println("File " + p + " does not exist in this directory");
        }
        if (Files.notExists(q)) {
            System.out.println("File " + q + " does not exist in this directory");
        }
    }
}

Output:

File /sample.txt exists in this directory.
File /xyz.txt does not exists in this directory.

 

ALSO READ: 3 ways to convert long to int in Java [Practical Examples]

Summary

The concept to check if a file exists or not is very useful. In many applications we need to perform some important operations that should not result into exception. So, it is very necessary to check if a file exists or not before proceeding with any other operations. We have covered three different ways to check if a file exists or not in Java with example. All in all, this tutorial, covers everything that you need to know in order to check the existence of file in Java.

How to check whether file exists or not in Java?

To test to see if a file or directory exists, use the exists method of the Java File class, as shown in this example: File tmpDir = new File("/var/tmp"); boolean exists = tmpDir. exists(); The existing method of the Java File class returns true if the file or directory exists, and false otherwise.

Which function is used to tell users whether a file exists or not?

While performing operations on files like writing or reading from a file, we need to first check if the file on which we are performing the particular operation exists or not. We use the is_file() function, which is part of the Path class from the pathlib module, or exists() function, which is part of the os.