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.
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.
If the src folder is empty it means there is no java files in project, so you can't run that project.
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.
You can directly use: FileUtils. deleteDirectory(<File object of directory>); This function will directory delete the folder and all files in it.
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With