You can check if a file exists in Java before working with it using the exists()
method from the File
class.
Following an example:
import java.io.File;
public class CheckFileExistsDemo {
public static void main(String[] args) {
// Specify the path and name of the file
String filePath = "C:\\path\\to\\your\\directory\\example.txt";
// Create a File object
File file = new File(filePath);
// Check if the file exists
if (file.exists()) {
System.out.println("File exists: " + file.getName());
// Perform your operations on the file here
// ...
} else {
System.out.println("File does not exist.");
}
}
}
Replace the filePath
with the actual path and name of your file. This code checks whether the file exists before proceeding with any operations. It’s a good practice to perform this check to avoid potential issues when working with files that may not be present.