How to check if a directory is empty in Java

How to check if a directory is empty in Java

To check if a directory is empty in Java, you can use the list() method of the File class or the Files class from the Java NIO.2 (Java 7 onwards). Here are two examples:

Using the File class (Java 6+):

import java.io.File; public class CheckEmptyDirectory { public static void main(String[] args) { File directory = new File("/path/to/your/directory"); if (directory.isDirectory()) { String[] files = directory.list(); if (files != null && files.length == 0) { System.out.println("The directory is empty."); } else { System.out.println("The directory is not empty."); } } else { System.out.println("The path does not point to a directory."); } } } 

Replace "/path/to/your/directory" with the actual path to the directory you want to check. This code first verifies if the path points to a directory and then checks if the list of files in the directory is empty.

Using the Files class (Java 7+):

import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.EnumSet; public class CheckEmptyDirectoryNIO2 { public static void main(String[] args) { Path directory = Paths.get("/path/to/your/directory"); if (Files.isDirectory(directory)) { try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) { if (!directoryStream.iterator().hasNext()) { System.out.println("The directory is empty."); } else { System.out.println("The directory is not empty."); } } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("The path does not point to a directory."); } } } 

Replace "/path/to/your/directory" with the actual path to the directory you want to check. This code uses the Java NIO.2 Files class to check if the directory is empty by creating a DirectoryStream and checking if it has any entries.

Both approaches will allow you to determine if a directory is empty or not. Choose the one that best fits your Java version and coding style.


More Tags

singleton guid sizewithfont websocket worksheet-function android-8.0-oreo query-optimization drive predicate discord

More Java Questions

More Chemical reactions Calculators

More Organic chemistry Calculators

More Transportation Calculators

More Statistics Calculators