How do I check if a file exists in Java

0 votes

If possible I'd prefer a real API call returning true/false as opposed to some "Call API to open a file and catch when it throws an exception which you check for 'no file' in the text", but I can live with the latter.

Dec 29, 2020 in Java by anonymous
• 8,910 points
62,817 views

4 answers to this question.

0 votes

Using java.io.File:

File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) { 
    // do something
}
answered Dec 29, 2020 by Gitika
• 65,910 points
0 votes

To test to see if a file or directory exists, use the exists method of the Java File class, as shown in this example:

File tmpDir = new File("/var/tmp");
boolean exists = tmpDir.exists();

The existing method of the Java File class returns true if the file or directory exists, and false otherwise.

Hope this helps!

Join java online course to learn more.

Thanks!

answered Dec 29, 2020 by Nikita

edited Jun 22, 2023 by Khan Sarfaraz
0 votes

The exists() function is a part of File class in Java . This function determines whether the is a file or directory denoted by the abstract filename exists or not.The function returns true if the abstract file path exists or else returns false.

Function signature:

public boolean exists()

Syntax:

file.exists()

// Java program to demonstrate

// exists() method of File Class

  

import java.io.*;

  

public class solution {

    public static void main(String args[])

    {

  

        // Get the file

        File f = new File("F:\\program.txt");

  

        // Check if the specified file

        // Exists or not

        if (f.exists())

            System.out.println("Exists");

        else

            System.out.println("Does not Exists");

    }

}

Output:

Exists
answered Dec 29, 2020 by Carlos
0 votes

To test to see if a file or directory exists, use the “exists()” method of the Java java.io.File class, as shown here:

File tempFile = new File("c:/temp/temp.txt");

boolean exists = tempFile.exists();

If above method returns true then file or directory does exist, and otherwise does not exists.

Check file exist with exists() method
import java.io.File;

import java.io.IOException;


public class TemporaryFileExample

{

   public static void main(String[] args)

   {

      File temp;

      try

      {

         temp = File.createTempFile("myTempFile", ".txt");

          

         boolean exists = temp.exists();

          

         System.out.println("Temp file exists : " + exists);

      } catch (IOException e)

      {

         e.printStackTrace();

      }

   }

}

Program Output.

Console

Temp file exists : true

answered Dec 29, 2020 by Rajiv
• 8,910 points