java.io.File class exists() method can be used to check if file exists or not in java. If file exists, it returns true else this method returns false.
Java Check if File Exists
Let’s look at a simple program to check if a file exists or not in Java.
package com.journaldev.files;
import java.io.File;
import java.io.IOException;
public class FileExists {
public static void main(String[] args) {
File file = new File("/Users/pankaj/source.txt");
File notExist = new File("xyz.txt");
try {
System.out.println(file.getCanonicalPath() + " exists? "+file.exists());
System.out.println(notExist.getCanonicalPath() + " exists? "+notExist.exists());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of the above program is:
/Users/pankaj/source.txt exists? true
/Users/pankaj/JavaPrograms/xyz.txt exists? false
Note: When we provide a relative path to create a file object, Eclipse uses project root as the base directory. If you are running the program from the command line, then the current directory is used as the base directory.
Read following post to know about java file path, canonical path and absolute path.
Thanks Pankaj for the explanation
Simple example with good coding practices and covering all cases :
private static void fetchIndexSafely(String url) throws FileAlreadyExistsException {
File f = new File(Constants.RFC_INDEX_LOCAL_NAME);
if (f.exists()) {
throw new FileAlreadyExistsException(f.getAbsolutePath());
} else {
try {
URL u = new URL(url);
FileUtils.copyURLToFile(u, f);
} catch (MalformedURLException ex) {
Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Reference
https://zgrepcode.com/examples/java/java/nio/file/filealreadyexistsexception-implementations