Check If A File Exists In A Directory In Java
In this instructional exercise, we will figure out or find out how to check whether a file exists in a directory or not through a simple Java code with examples.
Most of the time we need to perform certain operations in a file and before operating we need to check first whether the file we are including in the code exists in the directory or not.
File Whether Exists Or Not In A Directory
If you don’t know how to check whether a file exists or not in a directory through a code or program then you are at the right place.
After this exercise, you will be able to write a java program to check if a record exists in a registry.
Java ‘record exists’ tests:
To see if a file exists in a directory we can use the “exists” method of Java File class.
You can do it by including:
File file_obj=new File("FileCheck.txt"); boolean result=file_obj.exists();
The exists methods returns “true” if a file exists and returns “false” if it doesn’t.
To check whether a “FileCheck” is a file or Directory and to check, you can use “isDirectory()” method
You can do it by:
if(file.isDirectory()) System.out.println("FileCheck is a directory");
You can also check to identify whether it is truly a file or not and to check you can use the “isFile()” method in your java code.
You can do it by:
if("FileCheck.isFile()) System.out.println("FileCheck is a file");
Merging it all together, The below code will help you to achieve your goal:
import java.io.File; public class FileExistsCheck { public static void main(String[] args) { File file = new File("File1.txt"); boolean result = file.exists(); if(result && file.isFile()) { System.out.println("File1 exists and it is a file"); } //to check whether it is directory else if(file.isDirectory()) { System.out.println("File1 is a directory"); } else System.out.println("File1 is neither a file nor a directory"); } }
The output of the program is :
File1 exists and it is a file
Also, read:
- To determine whether string is rotated or not in Java (without using loops)
- Moving a file from One Directory to Another using Java
Leave a Reply