Computer Science, asked by yashrrtttt436, 1 year ago

How to check if a file exists or not in Java?

Answers

Answered by QGP
0

File Existence Check - Java

While doing File Handling in Java, there may arise the need to check if a given file or directory exists or not.

This can be done using a Simple Command: exists()

We need to import java.io and use the exists() function of the File Object.

For example, a simple code part would be this:

File fobj = New File("File Path");

System.out.println(fobj.exists());

The Function returns a boolean value:

  • True if the file or directory exists
  • False if the file or directory does not exist

Here's a Code Example. I have already created a file named test.txt

Apart from this, I have no file or directory named test2.txt

\rule{300}{1}

import java.io.*;

public class FileCheck  

{

   public static void main(String[] args) throws IOException

   {

       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

       System.out.print("Enter File Path: ");

       String path = br.readLine();

       File f = new File(path);

       if(f.exists())

       {

           System.out.println(path+" exists.");

       }

       else

       {

           System.out.println(path+" does not exist.");

       }

   }

}

Attachments:
Similar questions