I'd like to check if directory is empty in Java. But there is a possibility that there are many files in that directory so I'd like to do it without querying its file list, if possible.
11 Answers
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();
}
}
-
How would one go about if one would want to iterate over dirStream after the check? I tried: for (Path artifact : dirStream ) { But got a Iterator already obtained - Exception Jan 19, 2018 at 13:44
-
1@garyee, you could store the iterator in a local variable, then perform the
hasNext()
check as described in the answer and otherwise use awhile
loop over the iterator. Nov 5, 2019 at 21:40 -
You say
don't forget to close the stream
but in the example you don't close the stream? :)– jonrJun 9, 2020 at 14:21 -
7@jonr, he uses try-with-resources in the example so the stream is automatically closed when exiting the block.– FebtoberJun 22, 2020 at 13:54
-
The problem is that on Windows there is sometimes a desktop.ini file that is created by default. The method doesn't check for only that file. One could argue that this directory is not really empty, but it is empty of content user has created. Or am I missing something? Jan 2, 2021 at 8:35
File parentDir = file.getParentFile();
if(parentDir.isDirectory() && parentDir.list().length == 0) {
LOGGER.info("Directory is empty");
} else {
LOGGER.info("Directory is not empty");
}
-
7
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.
-
The javadoc for Files.list() says to close the stream when finished and suggests try-with-resources (and btw,
!isPresent()
is the same asisEmpty()
), so something like this:try (Stream<Path> entries = Files.list(path)) { return entries.findAny().isEmpty(); }
– ZyxlMay 16 at 12:22
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.
boolean isEmptyDirectory(Path dir) throws IOException {
try (var entries = Files.list(dir)) {
return entries.count() == 0;
}
}
Similar to @Minnow's solution (but with less method calls), this solution has the benefit "As Files.list Return a lazily populated Stream it will solve your execution time related issue."
-
2I guess count would load all the directory entries anyway. Wouldn't the
entries.findFirst().isPresent()
be a better solution? Jul 11, 2020 at 16:55 -
Both Files.list and Files.newDirectoryStream will iterate the directory entries lazily. Therefore, they will work with huge directories very efficiently. However, your solutions will not work well. It's not a good choice for huge directories.– NoNameOct 13, 2021 at 8:08
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.
-
15Directory deletion may fail due to other causes -- e.g., file permissions. May 8, 2011 at 20:31
-
1In fact it's ugly. Hope there is a 100% java solution for doing this. Still searching.– gd1May 8, 2011 at 20:46
-
I'd like people downvoting understand that I'm perfectly aware this is an horrible hack and I've done comprehensive research on how it can be done better, w/o finding anything satisfactory (see EDIT)– gd1May 8, 2011 at 20:58
-
3Well the problem is directory permissions - not just the wrong answer kind, but also the fact that you pretty much reset the permissions AND change metadata. Not much you can do about the second, but at least check permissions beforehand (that way you get rid of the false negative - just do a list() in that case) and set those permissions for the new dir. Still horrible, but a bit better.– VooMay 8, 2011 at 21:10
-
1I don't think even
/bin/ls
would work because it enumerates the whole directory in order to sort its output.– GabeMay 8, 2011 at 21:18
If you can live with platform dependent code - you can try using actual native code by loading a system library and using its APIs.
In Windows for example you have a Win32 API named FindFirstFile()
with the directory name (without a trailing backslash). If it returns something other than .
and ..
you know the directory isn't empty. It will not list all the files so it's much faster than file.list()
.
The equivalent on Unix is opendir
. For your purposes the logic would be the same.
Of course - calling native methods has a price on usability and the initial library loading which should be negated by the time it will save on the FS queries.
-
2Considering that there's absolutely nothing stopping people from creating files that don't contain a "." and nothing stopping people from creating directories that contain a "." - that solution won't do any good. And while I'm sure there's a more or less efficient way to do this with a native API, the overhead of calling it, will probably be worse. Depending on the FS implementation it's conceivable that the OS would have to enumerate all files in it to begin with anyways (no idea how NTFS is implemented?)– VooMay 8, 2011 at 20:43
-
@Voo: The proper usage is to ignore the
.
and..
entries. If a filesystem doesn't allow you to get the first directory entry without enumerating all the files, there would be no fast way to check if it's empty, but I doubt such a filesystem would ever exist.– GabeMay 8, 2011 at 21:16 -
@Gabe Yeah no idea how NTFS is implemented in detail. Your edited solution should be exactly what the OP wants, apart from the fact that it's native - and I'd assume the directory has to be quite large to offset the cost of the native call (but you mentioned that already and the question is about large dirs anyways so that's fine too). Though you should've created a new post (the edited one doesn't have much in common with the original ;) ), I'd love to upvote your post (or do you get a part of the credit because of your edit?)– VooMay 8, 2011 at 21:24
Path checkIfEmpty=Paths.get("Pathtofile");
DirectoryStream<Path> ds = Files.newDirectoryStream(checkIfEmpty);
Iterator files = ds.iterator();
if(!files.hasNext())
Files.deleteIfExists(Paths.get(checkIfEmpty.toString()));
-
6Just be careful to close DirectoryStream when you are done (or use try-with-resources) otherwise you end up with a file handler leak.– mp31415Mar 9, 2013 at 18:10
You can check whether directory
isDirectory()
after all (and not a file) and then, call list()
to get its content and finally, get the length
value to see whether there is content, i.e., whether it's not empty.
directory.isDirectory() && directory.list().length > 0 // directory is a File obj
-
1Welcome to stackoverflow. I'd recommend editing this to add how your answer is better or different from the many other answers already posted on this old question. Also note that the original question asks for a way to do this without calling
directory.list()
so if you still advise using it despite that, you should explain why. Apr 18 at 13:30 -
See "How to Answer" and Explaining entirely code-based answers". While this might be technically correct, it doesn't explain why it solves the problem or should be the selected answer. We should educate along with helping solve the problem. Apr 18 at 22:43
I also had this Confusion for a Long time about how to check if the Directory was empty or not But the Answer is Quite Simple use
class isFileEmpty{
public static void main(String args[]){
File d = new File(//Path of the Directory you want to check or open);
String path = d.getAbsolutePath().toString();
File dir = new File(path);
File[] files = dir.listFiles();
if(!dir.exists()){
System.out.Println("Directory is Empty");
}
else{
for(int i =0;i<files.length;i++){
System.out.Println(files[i])
}
}
}
}
I want to add to answer of Developer. Checking is it directory or not should not be in one If operator, because you will have mistake in logic. First of all you checking is it directory or not, and only after that you checking directory consistensy, becouse you will get wrong answer if the tranfered to method directory is not exist. Just check it. Should be like this:
if (file.isDirectory()) {
if( file.list().length == 0) {
logger.info("Directory is empty");
return false;
} else {
logger.info("Directory is not empty");
return true;
}
} else {
return false;
}
list()
can be very slow indeed. After flipping the logic (database query first), the runtime dropped to around 8 minutes.