Check Directory Empty Java
If you want to search directory and check if it is empty or not using java please have sample program below. We will use jdk 7 Files.newDirectoryStream open directory and use iterator to check if it is empty or not.
- Sample java program:
package com.javahonk; import java.io.File; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CheckDirectoryEmpty { public static void main(String[] args) { try { Path path = Paths.get("C:\\JavaHonk\\zip\\SpringMVCRESTFulService"); if (isDirectoryEmpty(path)) { System.out.println(path.getParent()+File.separator+path.getFileName()+ " is empty"); }else { System.out.println(path.getParent()+File.separator+path.getFileName()+ " is not empty"); } } catch (IOException e) { e.printStackTrace(); } } private static boolean isDirectoryEmpty(Path directory) throws IOException { try (DirectoryStreamdirectoryStream = Files.newDirectoryStream(directory)) { return !directoryStream.iterator().hasNext(); } } }
- Output:
For more information about Files API please check oracle documentation here
You need to close that DirectoryStream when you’re done with it, which you can do easily by wrapping it in a try-with-resources.
Thanks for info. Updated.