Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a directory is empty in Java

Tags:

java

file-io

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.

like image 363
Csq Avatar asked May 08 '11 20:05

Csq


People also ask

How do you check the file is empty or not in Java?

Well, it's pretty easy to check emptiness for a file in Java by using the length() method of the java. io. File class. This method returns zero if the file is empty, but the good thing is it also returns zero if the file doesn't exist.

Why is Java directory empty?

If the src folder is empty it means there is no java files in project, so you can't run that project.

How do you check if it is a directory in Java?

File. isDirectory() checks whether a file with the specified abstract path name is a directory or not. This method returns true if the file specified by the abstract path name is a directory and false otherwise.

How do you empty a folder in Java?

You can directly use: FileUtils. deleteDirectory(<File object of directory>); This function will directory delete the folder and all files in it.


2 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();     } } 
like image 101
Alan Avatar answered Oct 02 '22 07:10

Alan


File parentDir =  file.getParentFile(); if(parentDir.isDirectory() && parentDir.list().length == 0) {     LOGGER.info("Directory is empty"); } else {     LOGGER.info("Directory is not empty"); } 
like image 28
Divanshu Avatar answered Oct 02 '22 06:10

Divanshu