How to Check If a File Exists in Java


In this example we will show the method to check if a file exists in Java.

Source Code

package com.beginner.examples;

import java.io.*;

public class FileExists {

  public static void main(String[] args) {

    File f = new File("example.txt");
    if (f.exists()) { // check if a file exists
      System.out.println("The file existed.");
    } else {
      System.out.println("The file is not found!");
    }
  }
}

Output:

The file existed.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments