How to check a file exists or not in java.


 

How to check a file exists or not in java.

This tutorial demonstrate how to check for a file exists or not in java.

This tutorial demonstrate how to check for a file exists or not in java.

Description:

This example demonstrate how to check a file exits at a given path or not.  The method isFile() of the File class check for its existence. As in the file path we see '\' (backslash) that is used to denote file separation but here in this example File.separator is used.  

Code:

import java.io.File;

public class CheckFileExistence {
  public static void main(String[] a) {
    File findFile = new File("C:" + File.separator + "java-tutorial"
        + File.separator + "Test" + File.separator +
        
"anyfile.txt");
    System.out.println(findFile.isFile());
  }
}

Output:

The output of this example is either true or false depends on the file existence at the path that is set in the program above.

Ads