Java File exists() Method
Example
Check if two files exist (only filename.txt is created):
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
File myFile = new File("filename.txt");
myFile.createNewFile();
System.out.println(myFile.exists());
File otherFile = new File("nofile.txt");
System.out.println(otherFile.exists());
}
}
Definition and Usage
The exists() method checks if a file or directory exists.
A File object is only a path. Creating it does not create the file, so exists() tells you if the file is really there.
Syntax
public boolean exists()
Parameter Values
None.
Technical Details
| Returns: | true if the file or directory exists, otherwise false. |
|---|
Related Pages
❮ File Methods