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

public class FileChecker {
  public static void main(String args[]) {
	  File f = new File("c:\\mkyong.txt");
		  System.out.println("File existed");
		  System.out.println("File not found!");
Tags :

About the Author

Founder of and, 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.


  • 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

  • Piyush

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

  • Christian

    You just saved me a headache!!