How to check if a file exists in Java

To determine whether a file is exist in your file system, use the Java IO File.exists().

package com.mkyong.io;
 
import java.io.*;
 
public class FileChecker {
 
  public static void main(String args[]) {
 
	  File f = new File("c:\\mkyong.txt");
 
	  if(f.exists()){
		  System.out.println("File existed");
	  }else{
		  System.out.println("File not found!");
	  }
 
  }
 
}
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: Blue Coaster33()

  • Rajeev

    Here is the right solution:
    if (new File(“/Path/To/File/YourFileName.txt”).exists()){

    }

    If you are doing …
    File f = new File(“c:\\mkyong.txt”);
    and then checking the existence, it will always returns true because you are checking the existence after creating the file.

  • Dan

    @Piyush – If the file is remote you wouldn’t be telling the program to look for the file in the root of C:

  • Raymond

    This wont always work. f.exist also returns true when it’s a directory

  • http://stackoverflow.com/users/191797/piyush Piyush

    What if the file is remote? The above code snippet may fail

  • Christian

    You just saved me a headache!!