Check Directory Empty Java

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 (DirectoryStream directoryStream = Files.newDirectoryStream(directory)) {
			return !directoryStream.iterator().hasNext();
		}
	}

}
  • Output:

2014-11-30_1205

For more information about Files API please check oracle documentation here

2 thoughts on “Check Directory Empty Java”
  1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *