Check if file exists without creating it
Creating a File
instance does not create a file on the file system, so the posted code will do what you require.
Starting from Java 7 you can use java.nio.file.Files.exists
:
Path p = Paths.get("C:\\Users\\first.last");
boolean exists = Files.exists(p);
boolean notExists = Files.notExists(p);
if (exists) {
System.out.println("File exists!");
} else if (notExists) {
System.out.println("File doesn't exist!");
} else {
System.out.println("File's status is unknown!");
}
In the Oracle tutorial you can find some details about this:
The methods in the
Path
class are syntactic, meaning that they operate on thePath
instance. But eventually you must access the file system to verify that a particularPath
exists, or does not exist. You can do so with theexists(Path, LinkOption...)
and thenotExists(Path, LinkOption...)
methods. Note that!Files.exists(path)
is not equivalent toFiles.notExists(path)
. When you are testing a file's existence, three results are possible:
- The file is verified to exist.
- The file is verified to not exist.
- The file's status is unknown. This result can occur when the program does not have access to the file.
If both
exists
andnotExists
returnfalse
, the existence of the file cannot be verified.
When you instantiate a File
, you're not creating anything on disk but just building an object on which you can call some methods, like exists()
.
That's fine and cheap, don't try to avoid this instantiation.
The File
instance has only two fields:
private String path;
private transient int prefixLength;
And here is the constructor :
public File(String pathname) {
if (pathname == null) {
throw new NullPointerException();
}
this.path = fs.normalize(pathname);
this.prefixLength = fs.prefixLength(this.path);
}
As you can see, the File
instance is just an encapsulation of the path. Creating it in order to call exists()
is the correct way to proceed. Don't try to optimize it away.