How to check if File Exists in JAVA ?

If you want to check whether certain file is present or not in your disk before proceeding further to do some operations in JAVA, the java.io.File class provides an API “exists()” using which we can detect if file is present or not in your filesystem.

 $ vim FileExists.java 
import java.io.File;

public class FileExists {
        private static void checkIfFileExists(String fileName) {
                File filePointer = new File(fileName);
                if (filePointer.exists()) {
                        System.out.println("File: " + fileName + " is present");
                } else {
                        System.out.println("File: " + fileName + " is not present");
                }
        }

        public static void main(String[] args) throws Exception {
                checkIfFileExists("/usr/bin/adb");
                checkIfFileExists("/opt/xml"); //some random name for file, which may not be present
        }
}

As, we can see in above program, we passed two different argument to our written function checkIfFileExists, the first one is “/usr/bin/adb” which is a Android adb command and we had installed this prior to executing this program to demonstrate that our code detects its presence and shows that it exists and second is “/opt/xml” which is a non-existent directory.

Once we pass this two different agrument to “filePointer.exists()” , it detects “adb” presence whereas returns false for “xml” directory, as below

 $ javac FileExists.java 
 $ java FileExists 
File: /usr/bin/adb is present
File: /opt/xml is not present

The API definition is as below,

public boolean exists () – Tests whether the file or directory denoted by this abstract pathname exists. Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise

Next you can check “How to check if Filepsth is Normal File or Directory in JAVA ?”

Follow Lynxbee
Tags: , ,

Leave a Reply / Ask Question