- Check If a File or Directory Exists in Java
- Checking a File or Directory
- Verifying the Existence of a File or Directory
- Checking File Accessibility
- Checking Whether Two Paths Locate the Same File
- Java: Check if a File or Directory Exists
- Check if a File Exists
- Files.exists()
- Files.notExists()
- Files.isRegularFile()
- File.isFile()
- File.exists()
- Free eBook: Git Essentials
- Locked Files
- Check if a Directory Exists
- Files.exists()
- Files.isDirectory()
- Check if File is Symbolic Link
- Files.isSymbolicLink()
- File.getCanonicalPath() vs File.getAbsolutePath()
- Check if Either Exist
- Conclusion
- How to check if a directory exists in Java
- You might also like.
Check If a File or Directory Exists in Java
Learn to test if a file or a directory exists in a given path using Java standard IO and NIO APIs.
1. Using Files.exists() and Files.notExists()
Java NIO provides a few good ways to test whether the specified file or directory exists or not. Use Files.exists() method or Files.notExists() method for such validations.
Path path = Files.createTempFile("testFile", ".txt"); boolean exists = Files.exists(path); //true //OR Path tempDirectory = Files.createTempDirectory("temp-dir"); boolean exists = Files.notExists(tempDirectory); //false
By default, this method follows the symbolic links. Use the LinkOption#NOFOLLOW_LINKS if symbolic links are not to be followed.
Files.exists(symbolicLinkToFile, LinkOption.NOFOLLOW_LINKS)
2. Using Legacy File.exists()
To test to see if a file or directory exists, use the “ exists() ” method of the Java java.io.File class.
- If the exists() method returns true then the file or directory does exist and otherwise does not exists.
- If there is a read permission issue then it will throw SecurityException.
File tempFile = new File("c:/temp/temp.txt"); boolean exists = tempFile.exists();
3. Checking 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. You can need to build Path instances as discussed in the linked post.
final Path path = . ; Files.isReadable(path); //OR Files.isWritable(path); //OR Files.isExecutable(path);
That’s all for a quick tip related to checking if a file or directory exists or does not exists in java. Along with testing if the program is allowed to append content to it by checking its writable attribute.
Checking a File or Directory
You have a Path instance representing a file or directory, but does that file exist on the file system? Is it readable? Writable? Executable?
Verifying the Existence of a File or Directory
The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists, or does not exist. You can do so with the exists(Path, LinkOption. ) and the notExists(Path, LinkOption. ) methods. Note that !Files.exists(path) is not equivalent to Files.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 and notExists return false , the existence of the file cannot be verified.
Checking File Accessibility
To verify that the program can access a file as needed, you can use the isReadable(Path) , isWritable(Path) , and isExecutable(Path) methods.
The following code snippet verifies that a particular file exists and that the program has the ability to execute the file.
Path file = . ; boolean isRegularExecutableFile = Files.isRegularFile(file) & Files.isReadable(file) & Files.isExecutable(file);
Note: Once any of these methods completes, there is no guarantee that the file can be accessed. A common security flaw in many applications is to perform a check and then access the file. For more information, use your favorite search engine to look up TOCTTOU (pronounced TOCK-too).
Checking Whether Two Paths Locate the Same File
When you have a file system that uses symbolic links, it is possible to have two different paths that locate the same file. The isSameFile(Path, Path) method compares two paths to determine if they locate the same file on the file system. For example:
Path p1 = . ; Path p2 = . ; if (Files.isSameFile(p1, p2)) < // Logic when the paths locate the same file >
Java: Check if a File or Directory Exists
Checking if a file or directory exists is a simple and important operation in many tasks. Before accessing a file, we should check if it exists to avoid a NullPointerException . The same goes for directories.
While some functions may create a new file/directory if the requested one doesn’t exist, this may be the opposite of what we want. If we wish to append more information to an existing file and the method goes through without a warning, since it creates the new file it needs — we may have lost some information without realizing it.
Here, we’ve got a simple structure:
02/13/2020 11:53 AM directory 02/13/2020 11:55 AM directory_link [directory] 02/13/2020 11:53 AM 0 file.txt 02/13/2020 11:55 AM symlink.txt [file.txt]
There’s a file.txt file and a symlink.txt file. The symlink.txt file is a symbolic link to the file.txt .
Similarly, we’ve got a directory and a symbolic link to it — directory_link .
Check if a File Exists
To work with the Files class, you need to be acquainted with the Path class. Files only accepts Path , and not File objects.
For the purposes of the tutorial, we’ll define a File and Path instance for the file.txt in our directory:
final static String location = "C:\\file.txt"; Path path = Paths.get(location); File file = new File(location);
Files.exists()
That being said, the first way we can check if a file exists is through the Files class:
// Check if file exists through a Path System.out.println(Files.exists(path)); // Check if a file exists by converting File object to Path System.out.println(Files.exists(file.toPath()));
Running this code will yield us:
Files.notExists()
You might be wondering why the notExists() method exists at all:
If exists() returns true , that means that notExists() should return false . They’re logical complements and A = !B , right?
Well, that’s where many get it wrong. If Files.exists() returns false , it doesn’t have to mean that the file doesn’t exist.
It can also mean that the file’s existence cannot be verified. In that case, both Files.exists() and Files.notExists() would return false , as Java cannot determine if the file does or doesn’t exist.
This typically happens if you have a file that’s locked in a way that Java can’t access it. Imagine we had a file that’s locked in our directory — lockedFile.txt :
And if we tried verifying its existence with:
System.out.println(Files.exists(path)); System.out.println(Files.notExists(path));
It exists, obviously, but Java doesn’t have permission to confirm that on our system — thus giving conflicting results.
Files.isRegularFile()
Additionally, we can check if the file is a regular file ( false if it’s a directory) through the isRegularFile() method:
System.out.println(Files.isRegularFile(path));
File.isFile()
Instead of using the Files class, we can also perform methods on the file objects themselves:
System.out.println(file.isFile());
File.exists()
Similar to the previous option, we can run the exists() method:
System.out.println(file.exists());
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
The difference between these two is that the first one checks if it’s a file, and the other one checks if it exists. In different circumstances, they’d return different results.
Locked Files
A fun thing to note is that if you’re using a File to check for existence, Java can determine if the locked file from before exists or not:
System.out.println(file.isFile()); System.out.println(file.exists());
Running this piece of code will yield:
With this, it’s evident that the locked file can be read by using the File class instead of the Files helper class.
Check if a Directory Exists
Directories are essentially files, that can contain other files. This is why checking if a directory is a file will return true . Though, if you’re checking if a directory is a directory (a special type of file), you’ll get a more accurate result.
This time around, we’re switching our location to:
final static String location = "C:\\directory";
Files.exists()
Again, just like in the first example, we can check if it exists via:
System.out.println(Files.exists(path));
Files.isDirectory()
If we’d like to check if it’s specifically a directory, we’d use:
System.out.println(Files.isDirectory(path));
Note: If the directory doesn’t exist, the isDirectory() method will return false . It’s due to the way the method is named. What it does is — it checks if the file exists and if it’s a directory, not only the latter. A file can’t be a directory if it doesn’t exist — hence, false is returned.
Check if File is Symbolic Link
You might also want to check if a file is just a symbolic link. In that case, you’d use the Files class.
Let’s switch our location to:
final static String location = "C:\\symlink.txt";
Files.isSymbolicLink()
As usual, the Files class accepts a Path to the file:
System.out.println(Files.isSymbolicLink(path));
File.getCanonicalPath() vs File.getAbsolutePath()
Another way to check for a symbolic link is to compare the results of the file’s canonical path and absolute path. If they’re different, it’s most probably a symbolic link:
System.out.println(file.getCanonicalPath()); System.out.println(file.getAbsolutePath());
Since we’re checking for a symbolic link, and we know it is, these should return a different result — a symlink.txt and file.txt path:
However, this isn’t the case here. This is due to the fact that the symlink was created on Windows with NTFS (New Technology File System). The symlink was created using the mklink command in the CMD.
Check if Either Exist
From the previous examples, it’s evident that the Files.exists() method will return true for both existing files and directories. Though, it doesn’t work best when it comes to locked files.
On the other hand, the exists() method from the File class will also return true for both files and directories and can read the locked file that the Files class can’t.
Conclusion
Checking for the existence of files and directories is the first line of defense against missing files and directories. Different approaches have different setbacks and you might assume that a method will return an accurate result, but it won’t due to how it works in the background.
Being aware of which methods return which results in which circumstances will allow you to avoid nasty exceptions when handling files.
After checking if your file exists or not, you’ll likely want to do some Reading and Writing Files in Java.
How to check if a directory exists in Java
In the previous article, we looked at how to check if a regular file exists in Java. In this short article, you’ll learn how to check if a directory exists in the file system using Java.
In Java 7 and higher, you can use the NIO API Files.isDirectory() static method to check if a folder exists in your file system:
if (Files.isDirectory(Paths.get("/var/lib/"))) System.out.println("Directory found."); > else System.out.println("Directory not found."); >
To make sure that the directory is not a symbolic link, you can pass LinkOption.NOFOLLOW_LINKS :
if (Files.isDirectory(Paths.get("/var/lib/"), LinkOption.NOFOLLOW_LINKS)) System.out.println("Directory found."); > else System.out.println("Directory not found."); >
In Java 6 or below, you can use File.isDirectory() method to check for directory existence in Java as shown below:
File file = new File("/var/lib/"); // check if directory exists if (file.isDirectory()) System.out.println("Directory found."); > else System.out.println("Directory not found."); >
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.