Check If a File or Directory Exists in Java

1. Overview

In this quick tutorial, we’re going to get familiar with different ways to check the existence of a file or directory.

First, we’ll start with the modern NIO APIs and then will cover the legacy IO approaches.

2. Using java.nio.file.Files

To check if a file or directory exists, we can leverage the Files.exists(Path) method. As it’s clear from the method signature, we should first obtain a Path to the intended file or directory. Then we can pass that Path to the Files.exists(Path) method:

1
2
Path path = Paths.get("does-not-exist.txt");
assertFalse(Files.exists(path));

Since the file doesn’t exist, it returns false. It’s also worth mentioning that if the Files.exists(Path) method encounters an IOException, it’ll return false, too.

On the other hand, when the given file exists, it’ll return true as expected:

1
2
Path tempFile = Files.createTempFile("maixuanviet", "exist-article");
assertTrue(Files.exists(tempFile));

Here we’re creating a temporary file and then calling the Files.exists(Path) method.

This even works for directories:

1
2
Path tempDirectory = Files.createTempDirectory("maixuanviet-exists");
assertTrue(Files.exists(tempDirectory));

If we specifically want to know if a file or directory exists, we can also use Files.isDirectory(Path) or Files.isRegularFile(Path) methods:

1
2
3
assertTrue(Files.isDirectory(tempDirectory));
assertFalse(Files.isDirectory(tempFile));
assertTrue(Files.isRegularFile(tempFile));

There is also a notExists(Path) method that returns true if the given Path doesn’t exist:

1
assertFalse(Files.notExists(tempDirectory));

Sometimes the Files.exists(Path) returns false because we don’t possess the required file permissions. In such scenarios, we can use the Files.isReadable(Path) method to make sure the file is actually readable by the current user:

1
2
assertTrue(Files.isReadable(tempFile));
assertFalse(Files.isReadable(Paths.get("/root/.bashrc")));

2.1. Symbolic Links

By default, the Files.exists(Path) method follows the symbolic links. If file has a symbolic link to file B, then the Files.exists(A) method returns true if and only if the file exists already:

1
2
3
4
Path target = Files.createTempFile("maixuanviet", "target");
Path symbol = Paths.get("test-link-" + ThreadLocalRandom.current().nextInt());
Path symbolicLink = Files.createSymbolicLink(symbol, target);
assertTrue(Files.exists(symbolicLink));

Now if we delete the target of the link, the Files.exists(Path) will return false:

1
2
Files.deleteIfExists(target);
assertFalse(Files.exists(symbolicLink));

Since the link target doesn’t exist anymore, following the link won’t lead to anything, and Files.exists(Path) will return false.

It’s even possible to not follow the symbolic links by passing an appropriate LinkOption as the second argument:

1
assertTrue(Files.exists(symbolicLink, LinkOption.NOFOLLOW_LINKS));

Because the link itself exists, the Files.exists(Path) method returns true. Also, we can check if a Path is a symbolic link using the Files.isSymbolicLink(Path) method:

1
2
assertTrue(Files.isSymbolicLink(symbolicLink));
assertFalse(Files.isSymbolicLink(target));

3. Using java.io.File

If we’re using Java 7 or a newer version of Java, it’s highly recommended to use the modern Java NIO APIs for these sorts of requirements.

However, to make sure if a file or directory exists in Java legacy IO world, we can call the exists() method on File instances:

1
assertFalse(new File("invalid").exists());

If the file or directory does exist already, it’ll return true:

1
2
3
4
5
6
7
8
Path tempFilePath = Files.createTempFile("maixuanviet", "exist-io");
Path tempDirectoryPath = Files.createTempDirectory("maixuanviet-exists-io");
 
File tempFile = new File(tempFilePath.toString());
File tempDirectory = new File(tempDirectoryPath.toString());
 
assertTrue(tempFile.exists());
assertTrue(tempDirectory.exists());

As shown above, the exists() method doesn’t care if it’s a file or directory. Therefore, as long as it does exist, it’ll return true

The isFile() method, however, returns true if the given path is an existing file:

1
2
assertTrue(tempFile.isFile());
assertFalse(tempDirectory.isFile());

Similarly, the isDirectory() method returns true if the given path is an existing directory:

1
2
assertTrue(tempDirectory.isDirectory());
assertFalse(tempFile.isDirectory());

Finally, the canRead() method returns true if the file is readable:

1
2
assertTrue(tempFile.canRead());
assertFalse(new File("/root/.bashrc").canRead());

When it returns false, the file either doesn’t exist or the current user doesn’t possess the read permission on the file.

4. Conclusion

In this short tutorial, we saw how to make sure a file or directory exists in Java. Along the way, we talked about modern NIO and the legacy IO APIs. Also, we saw how the NIO API handles symbolic links.

As usual, all the examples are available over on GitHub.

Related posts:

Chuyển đổi Array sang ArrayList và ngược lại
Java Program to Implement Merge Sort Algorithm on Linked List
Iterable to Stream in Java
Java Program to Implement Dijkstra’s Algorithm using Priority Queue
Spring Boot Gradle Plugin
Java Program to Check if an UnDirected Graph is a Tree or Not Using DFS
Java Program to Implement ScapeGoat Tree
Java Program to Implement the Monoalphabetic Cypher
Introduction to the Java ArrayDeque
Spring Data Reactive Repositories with MongoDB
Java Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers
Circular Dependencies in Spring
Java Program to Implement LinkedBlockingQueue API
OAuth2 for a Spring REST API – Handle the Refresh Token in AngularJS
Java Program to Implement the Vigenere Cypher
Guide to Java OutputStream
Guide to java.util.Formatter
Java List UnsupportedOperationException
Java Program to Solve Set Cover Problem assuming at max 2 Elements in a Subset
Control Structures in Java
Summing Numbers with Java Streams
Java Program to Perform Finite State Automaton based Search
The DAO with Spring and Hibernate
Uploading MultipartFile with Spring RestTemplate
Java Program to Implement Fenwick Tree
Lấy ngày giờ hiện tại trong Java
Guide to java.util.concurrent.BlockingQueue
Spring Boot - Build Systems
Java Program to Implement Heap’s Algorithm for Permutation of N Numbers
So sánh HashMap và HashSet trong Java
Java Program to find the number of occurrences of a given number using Binary Search approach
Introduction to Spring Data JPA