This post guides you to check a file exist or not in the Java programming language. The Java File API has a method exists() that returns a boolean value.
Syntax
boolean java.io.File.exists()
This tests whether the file or directory denoted by the abstract filename exists or not. This method does not take any parameter as input.
The exists() method returns true if the abstract file path exists or otherwise returns false.
Program
package com.digitizedpost.files;
import java.io.File;
import java.io.IOException;
public class CheckFileExists {
public static void main(String[] args) {
try {
isFileExists();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void isFileExists() throws IOException {
File file1 = new File("C:\\TutorialTemp\\Spring Boot Tutorial.txt");
File file2 = new File("C:\\Tutorial\\Spring Boot Tutorial1.txt");
System.out.println("Parent : " + file1.getParent());
System.out.println("Parent File : " + file1.getParentFile());
System.out.println("Canonical File : " + file1.getCanonicalFile());
System.out.println(file1.getParentFile().exists());
System.out.println(file1.getCanonicalFile().exists());
if (!file1.getParentFile().exists()) {
System.out.println("File 1. Parent File Not Exists");
file1.getParentFile().mkdir();
file1.createNewFile();
} else {
System.out.println("File 1. Parent File Exists");
}
if (!file2.getParentFile().exists()) {
System.out.println("File 2. Parent File Not Exists");
file2.getParentFile().mkdir();
} else if (!file2.exists()) {
System.out.println(file1.getName() + " File Not Exists");
file2.createNewFile();
} else {
System.out.println("File 2. Parent File Exists");
}
}
}
Here we have demonstrated with 2 files and one is with an incorrect path or missing file name. We have used mkdir() method here, There is also another plural method mkdirs() in Java File API. The difference is explained in another post.
Here is the explanation for the above program,
- If the folder TutorialTemp doesn't exist we are creating a new folder and
- If the file Spring Boot Tutorial1.txt doesn't exist we are creating a new file.
Output
Parent : C:\TutorialTemp
Parent File : C:\TutorialTemp
Canonical File : C:\TutorialTemp\Spring Boot Tutorial.txt
false
false
File 1. Parent File Not Exists
Spring Boot Tutorial.txt File Not Exists