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 class provides an API “exists()” using which we can detect if file is present or not in your filesystem.

 $ vim 

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("/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 
 $ 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 ?”

Android Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense NDK / Middleware / HAL OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized User Interface Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply / Ask Question