How to check if a directory is empty in Java
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();
}
}
File parentDir = file.getParentFile();
if(parentDir.isDirectory() && parentDir.list().length == 0) {
LOGGER.info("Directory is empty");
} else {
LOGGER.info("Directory is not empty");
}