
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements