In this tutorial, we will learn how can we test to check if file exists or a directory exist in given path in Java.
1. Check if file exists with File.exists() method
To test to see if a file or directory exists, use the “exists()
” method of the Java java.io.File class, as shown here:
File tempFile = new File("c:/temp/temp.txt"); boolean exists = tempFile.exists();
If above method returns true
then file or directory does exist, and otherwise does not exists.
import java.io.File; import java.io.IOException; public class TemporaryFileExample { public static void main(String[] args) { File temp; try { temp = File.createTempFile("myTempFile", ".txt"); boolean exists = temp.exists(); System.out.println("Temp file exists : " + exists); } catch (IOException e) { e.printStackTrace(); } } }
Program Output.
Temp file exists : true
2. Files.exists() and Files.notExists() methods
Java NIO also provides good ways to test whether a file exists or not. Use Files.exists()
method or Files.notExists()
method for this.
final Path path = Files.createTempFile("testFile", ".txt"); Files.exists(path); //true //OR Files.notExists(path); //false
3. Check if file is readable, writable or executable
To verify that the program can access a file as needed, you can use the isReadable(Path), isWritable(Path), and isExecutable(Path) methods.
Java program to test a file if it is readable, writable and executable.
final Path path = ...; Files.isReadable(path); //OR Files.isWritable(path); //OR Files.isExecutable(path);
That’s all for quick tip related to checking if a file or directory exists or does not exists in java. Along with test if program is allowed to append content to it by checking it’s writable attribute.
Happy Learning !!
Reference:
Vijay
Hi All ,
I need to check , for a particular parameter value exists in a file which exists in multiple virtual machines.
Please help with the logic.
Thanks,
VIjay
Himansu
Hi Lokesh,
Can you elaborate more on how Files.notExists() is different from ! (Files.exists()) . Actually both of there source codes looks very much alike.
Thanks,
Himansu
Lokesh Gupta
You guess what.. you are absolutely right.. 🙂