To check if a file, or a directory exists we can utilize java.io.File.exists()
method. This method return either true
or false
. Before we can check whether its exists or not we need to create an instance of File
that represent an abstract path name of the file or directory. After we have the File
instance we can call the exists()
method to validate it.
package org.kodejava.io;
import java.io.File;
import java.io.FileNotFoundException;
public class FileExists {
public static void main(String[] args) throws Exception {
// Create an abstract definition of configuration file to be
// read.
File file = new File("applicationContext-hibernate.xml");
// Print the exact location of the file in file system.
System.out.println("File = " + file.getAbsolutePath());
// If configuration file, applicationContext-hibernate.xml
// does not exist in the current path throws an exception.
if (!file.exists()) {
String message = "Cannot find configuration file!";
System.out.println(message);
throw new FileNotFoundException(message);
}
// Continue with application logic here!
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024