# Check if a directory is not empty in Java

Java 8Object Oriented ProgrammingProgramming

The method java.io.File.list() is used to obtain the list of the files and directories in the specified directory defined by its path name. This list of files is stored in a string array. If the length of this string array is greater than 0, then the specified directory is not empty. Otherwise, it is empty.

A program that demonstrates this is given as follows −

## Example

Live Demo

import java.io.File;
public class Demo {
public static void main(String[] args) {
File directory = new File("C:\\JavaProgram");
if (directory.isDirectory()) {
String[] files = directory.list();
if (directory.length() > 0) {
System.out.println("The directory " + directory.getPath() + " is not empty");
} else {
System.out.println("The directory " + directory.getPath() + " is empty");
}
}
}
}

The output of the above program is as follows −

## Output

The directory C:\JavaProgram is not empty

Now let us understand the above program.

The method java.io.File.list() is used to obtain the list of the files and directories in the directory "C:\\JavaProgram". Then this list of files is stored in a string array files[]. If the length of this string array is greater than 0, then the specified directory is not empty is this is printed. Otherwise, it is empty is that is printed. A code snippet that demonstrates this is given as follows −

File directory = new File("C:\\JavaProgram");
if (directory.isDirectory()) {
String[] files = directory.list();
if (directory.length() > 0) {
System.out.println("The directory " + directory.getPath() + " is not empty");
} else {
System.out.println("The directory " + directory.getPath() + " is empty");
}
}
Published on 28-Feb-2019 11:19:17