How to check if a directory is empty in Java

Solution 1:

With JDK7 you can use Files.newDirectoryStream to open the directory and then use the iterator's hasNext() method to test there are any files to iterator over (don't forgot to close the stream). This should work better for huge directories or where the directory is on a remote file system when compared to the java.io.File list methods.

Example:

private static boolean isDirEmpty(final Path directory) throws IOException {
    try(DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory)) {
        return !dirStream.iterator().hasNext();
    }
}

Solution 2:

File parentDir =  file.getParentFile();
if(parentDir.isDirectory() && parentDir.list().length == 0) {
    LOGGER.info("Directory is empty");
} else {
    LOGGER.info("Directory is not empty");
}

Solution 3:

if(!Files.list(Paths.get(directory)).findAny().isPresent()){
    Files.delete(Paths.get(directory));
 }

As Files.list Return a lazily populated Stream it will solve your execution time related issue.

Solution 4:

Considering from java.io.File source code, list() method does:

    public java.lang.String[] list() {
    ...
        byte[][] implList = listImpl(bs);
        if (implList == null) {
           // empty list
           return new String[0];
        }     
     ...
     }

     private synchronized static native byte[][] listImpl(byte[] path);

It calls a native method passing a byte array to get files from it. If a method returns null it means directory is empty.

Which means, they don't even have a native method, to check for directory emptiness without listing files, so there is no way they would have an implementation in java for checking if directory is empty.

Outcome: checking if directory is empty without listing files is not implemented in java, yet.

Solution 5:

This is a dirty workaround, but you can try do delete it (with the delete method), and if the delete operation fails, then the directory is not empty, if it succeeds, then it is empty (but you have to re-create it, and that's not neat). I'll continue searching for a better solution.

EDIT: I've found walkFileTree from java.nio.file.Files class: http://download.java.net/jdk7/docs/api/java/nio/file/Files.html#walkFileTree(java.nio.file.Path, java.nio.file.FileVisitor) Problem is that this is Java 7 only.

I've searched S.O. for other questions related to this very issue (listing files in a directory w/o using list() which allocates memory for a big array) and the answer is quite always "you can't, unless you use JNI", which is both platform dependent and ugly.