How to check if file exists in Java

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.

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 exists() 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.

There is one more issue with only using the exists() 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 isDirectory() also to make sure that the given argument is a file but not a directory.

The syntax of exists method is as shown below.

java

    fileobject.exists()
 

ALSO READ:
Unary Operators in Java Explained [Practical Examples]
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.

java

// 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:

bash

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

Method-2: Using isFile method of File class
Prior to the Java SE 7 release, the isFile() 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.


The advantage of using the isFile() method over the exists() method is that we will not have to check if the given file is a directory or not. Unlike, exists() method this file will not return True for directory.

The syntax of isFile method is as shown below.

java

    fileobject.isFile()
Example :

java

// 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:

bash

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 split String into Array [Practical Examples]
Method-3: Using NIO
From Java 7 onward, the exists() method of java.nio.file.Files is a static method that returns true if the file exists. Whereas, the notExists() method returns true when it does not exist. Moreover, if both exists() and notExists() return false, 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 Files.exists() returns true when your path points to a directory. So, it is recommended to use this method along with the Files.isDirectory() method, which checks the file for a directory.

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

bash

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 Files.exists() method.

java

// 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:

bash

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

ALSO READ:
Java Booleans Explained [Easy 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.

References
Legacy File I/O
Files

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值