Java: Check if File or Directory is Empty

Introduction

In Java, working with files and directories is rather common. We are also often interested in the contents of those files and directories.

Depending on the contents of the file, we might want to behave differently. We might be writing some data into a file and we first want to check if it already contains some information before overwriting it. Similarly, we might be wanting to delete a directory if it's empty. The knowledge of whether it's empty or not can, in such cases, be of vital importance.

In this tutorial, we'll go over some examples of how to check if a file or directory is empty in Java.

Check if a File is Empty in Java

There are two ways to check if a File is empty.

We'll be working with two files, one empty and one non-empty:

09/17/2020  01:00 PM                 0 file
09/17/2020  01:00 PM                 2 file2

file is 0 bytes in length, while file2 is 2 bytes in length.

It's worth noting that before performing any operations on a file or directory, you should check if a file or directory exists, as well as their type to avoid running the wrong methods.

Using File.length()

According to its documentation, a File object is "an abstract representation of file and directory pathnames". Each File object has methods for obtaining information about that specific file.

Let's go ahead and create a simple helper method that returns true if the File's length is 0 and false otherwise:

public boolean isFileEmpty(File file) {
    return file.length() == 0;
}

Now, let's test it out on an empty and non-empty file:

File file1 = new File("/file");
File file2 = new File("/file2");

System.out.println(isFileEmpty(file1));
System.out.println(isFileEmpty(file2));

This code returns:

true
false

Using BufferedReader

Another way to check if the File's length is 0 or not is to use the BufferedReader. It allows us to reach character contents from streams (such as files). If there are no contents in the file, it's empty:

public boolean isFileEmpty(File file) {
    BufferedReader br = new BufferedReader(new FileReader(file));     
    return br.readLine() == null;
}

The method's declaration remains the same as before: it accepts a File and returns a boolean. Though this time, we've instantiated a BufferedReader and provided it with a FileReader which accepts our File. It's slightly more complex than before but it gets the job done just as well.

Then, if the BufferedReader has nothing to read from the file, we know it's empty.

Again, let's test this out on an empty and a non-empty file:

File file1 = new File("/file");
File file2 = new File("/file2");

System.out.println(isFileEmpty(file1));
System.out.println(isFileEmpty(file2));

This code returns:

true
false

Check if Directory is Empty in Java

There's two ways to check if a directory is empty in Java, as well.

Using File.list()

The File class has a convenient method for collecting all files and directories (entries, meaning both files and directories) inside a given directory. We can use this method to check if the number of such entries is zero:

public boolean isDirectoryEmpty(File directory) {  
    String[] files = directory.list();
    return files.length == 0;  
}
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 method returns an array of entry names. If the length of this array is 0, the directory is empty.

Let's run this on an empty and non-empty directory:

File directory1 = new File("/empty_directory");
File directory2 = new File("/directory");

System.out.println(isDirectoryEmpty(directory1));
System.out.println(isDirectoryEmpty(directory1));

This returns:

true
false

Using a DirectoryStream

Another quick, albeit more advanced, technique involves using streams. First, we create a new DirectoryStream by calling Files.newDirectoryStream() class. This method accepts a Path so we need to convert our File into a Path by calling the toPath() method:

public boolean isDirectoryEmpty(File directory) throws IOException {
    DirectoryStream<Path> stream = Files.newDirectoryStream(directory.toPath());
    return !stream.iterator().hasNext();  
}

Then, we collect the stream's iterator and check if it contains a next entry by calling hasNext(). If it doesn't contain at least one entry, the directory is empty.

Let's run this code:

File directory1 = new File("/empty_directory");
File directory2 = new File("/directory");

System.out.println(isDirectoryEmpty(directory1));
System.out.println(isDirectoryEmpty(directory1));

And this results in:

true
false

Conclusion

In this tutorial, we've laid down a few examples for checking whether files and directories are empty. First, we've checked if files are empty using the File class and its length() method, followed by a BufferedReader approach.

Then, we've checked if a directory is empty by using File.list() and by creating a DirectoryStream.

Last Updated: September 22nd, 2020
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms