Check Whether a File Exists in Java



In this article, we will learn how to check whether a file exists using Java. The program demonstrates the use of the exists() method from the java.io.File class to perform this check.

Java.io.File.exists() Method

The java.io.File.exists() method returns true if the file path exists, otherwise it returns false. Parameters: This method does not take any parameters. Return Value: It returns a boolean indicating whether the file specified by the abstract path exists.

Checking whether a file exists or not in Java

The following are the steps to check whether a file exists or not ?

  • Step 1. Use Try-Catch Block: A try-catch block is used for any exceptions that might occur during file creation or checking.
  • Step 2. Create a File Object: A File object is created with the file name "demo1.txt".
File file = new File("demo1.txt");
  • Step 3. Create a New File: The createNewFile() method is called to create the file if it doesn't exist.
file.createNewFile();
  • Step 4. Check File Existence: The exists() method is used to check if the file exists.

Java program to check whether a file exists or not

A program that demonstrates this is given as follows ?

import java.io.File;
public class Demo {
	public static void main(String[] args) {
		try {
			File file = new File("demo1.txt");
			file.createNewFile();
			System.out.println("File exists? " + file.exists());
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

Output

File exists? true
Updated on: 2024-11-23T03:51:25+05:30

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements