
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 If File Exists Anywhere on the System in Java
You can verify whether a particular file exists in the system in two ways using the File class and using the Files class.
Using The File class
The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.
This class provides various methods to manipulate files, The exists a () method of it verifies whether the file or directory represented by the current File object exists if so, it returns true else it returns false.
Example
The following Java program verifies whether a specified file exists in the system. It uses the methods of the File class.
import java.io.File; public class FileExists { public static void main(String args[]) { //Creating a File object File file = new File("D:\source\sample.txt"); //Verifying if the file exits boolean bool = file.exists(); if(bool) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } }
Output
File exists
The Files class
Since Java 7 the Files class was introduced this contains (static) methods that operate on files, directories, or other types of files.
The class to provides a method named exists(), which returns true if the file represented by the current object(s) exists in the system else it returns false.
Example
The following Java program verifies whether a specified file exists in the system. It uses the methods of the Files class.
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileExists { public static void main(String args[]) { //Creating a Path object Path path = Paths.get("D:\sample.txt"); //Verifying if the file exits boolean bool = Files.exists(path); if(bool) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } } }
Output
File does not exist