How to Check if File exists in Java

Filed Under: Java class exists() method can be used to check if file exists or not in java. If file exists, it returns true else this method returns false.

Java Check if File Exists

Let’s look at a simple program to check if a file exists or not in Java.

package com.journaldev.files;


public class FileExists {

    public static void main(String[] args) {
        File file = new File("/Users/pankaj/source.txt");
        File notExist = new File("xyz.txt");
        try {
            System.out.println(file.getCanonicalPath() + " exists? "+file.exists());
            System.out.println(notExist.getCanonicalPath() + " exists? "+notExist.exists());
        } catch (IOException e) {


Output of the above program is:

/Users/pankaj/source.txt exists? true
/Users/pankaj/JavaPrograms/xyz.txt exists? false

Note: When we provide a relative path to create a file object, Eclipse uses project root as the base directory. If you are running the program from the command line, then the current directory is used as the base directory.

Read following post to know about java file path, canonical path and absolute path.

You can checkout more Java IO examples from our GitHub Repository.


  1. Dylan Smith says:

    Thanks Pankaj for the explanation
    Simple example with good coding practices and covering all cases :

    private static void fetchIndexSafely(String url) throws FileAlreadyExistsException {
    File f = new File(Constants.RFC_INDEX_LOCAL_NAME);
    if (f.exists()) {
    throw new FileAlreadyExistsException(f.getAbsolutePath());
    } else {
    try {
    URL u = new URL(url);
    FileUtils.copyURLToFile(u, f);
    } catch (MalformedURLException ex) {
    Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
    Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);


Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content