- How to Check if a File or a Directory Exists in Java
- Check if File Exists (Java NIO)
- Check if Directory Exists (Java NIO)
- Check if File Exists (Java Legacy IO)
- Check if Directory Exists (Java Legacy IO)
- 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
- Java does path exist
- Uses of Path in java.io
- Uses of Path in java.nio.channels
- Uses of Path in java.nio.file
- Uses of Path in java.nio.file.spi
How to Check if a File or a Directory Exists in Java
In Java, there are two primary methods of checking if a file or directory exists. These are:
1 — Files.exists from NIO package
2 — File.exists from legacy IO package
Let’s see some of the examples from each package.
Check if File Exists (Java NIO)
The code uses Path and Paths from the Java NIO package to check if a file exists:
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CheckFileExist < public static void main(String[] args) < Path path = Paths.get("/path/to/file/app.log"); if (Files.exists(path)) < if (Files.isRegularFile(path)) < System.out.println("App log file exists"); >> else < System.out.println("App log file does not exists"); >> >
Check if Directory Exists (Java NIO)
Likewise, if we wanted to check if a directory exists in Java using the NIO package:
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CheckDirectoryExist < public static void main(String[] args) < Path path = Paths.get("/path/to/logs/"); if (Files.exists(path)) < if (Files.isDirectory(path)) < System.out.println("Logs directory exists"); >> else < System.out.println("Logs directory does not exist"); >> >
Check if File Exists (Java Legacy IO)
If you’re not using Java NIO package, you can use the legacy Java IO package:
import java.io.File; public class CheckFileExists < public static void main(String[] args) < File file = new File("/path/to/file/app.log"); if(file.exists()) < System.out.println("App log file exists"); >else < System.out.println("App log file does not exist"); >> >
Check if Directory Exists (Java Legacy IO)
Similarly, to check directory we can use:
import java.io.File; public class CheckFileExists < public static void main(String[] args) < File file = new File("/path/to/logs/"); if(file.isDirectory()) < System.out.println("Logs directory exists"); >else < System.out.println("Logs directory does not exist"); >> >
Further reading
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.
Java does path exist
Defines channels, which represent connections to entities that are capable of performing I/O operations, such as files and sockets; defines selectors, for multiplexed, non-blocking I/O operations.
Defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems.
Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).
Uses of Path in java.io
Uses of Path in java.nio.channels
Modifier and Type | Method and Description |
---|---|
static AsynchronousFileChannel | AsynchronousFileChannel. open (Path file, OpenOption. options) |
Opens or creates a file for reading and/or writing, returning an asynchronous file channel to access the file.
Opens or creates a file for reading and/or writing, returning an asynchronous file channel to access the file.
Uses of Path in java.nio.file
Modifier and Type | Field and Description |
---|---|
static WatchEvent.Kind | StandardWatchEventKinds. ENTRY_CREATE |
Creates a new directory in the default temporary-file directory, using the given prefix to generate its name.
Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name.
Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.
Returns the root component of this path as a Path object, or null if this path does not have a root component.
Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the resolve method.
Converts a given path string to a Path and resolves it against this path’s parent path in exactly the manner specified by the resolveSibling method.
Return a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file.
Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.
Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.
Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name.
Return a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file.
Opens a file for reading, returning a BufferedReader to read text from the file in an efficient manner.
Opens a file for reading, returning a BufferedReader that may be used to read text from the file in an efficient manner.
Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner.
Opens or creates a file for writing, returning a BufferedWriter to write text to the file in an efficient manner.
Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.
Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.
Return a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file.
Uses of Path in java.nio.file.spi
Modifier and Type | Method and Description |
---|---|
abstract Path | FileSystemProvider. getPath (URI uri) |
Opens or creates a file for reading and/or writing, returning an asynchronous file channel to access the file.