The list() method defined in class java.io.File which is used to obtain the list of files and folders(directories) present in the specified directory defined by its pathname. The list of files is stored in an array of string. If the length of an array is greater than 0, then the specified directory is not empty, else it is empty.
Method 1: Use of list() method
- Suppose there is a directory present in the path /home/user/folder and it has three text files.
- Create an array and store the name of files using the list() method.
- Calculate the length of a string array
- Print result
See the below program for the above approach.
Java
import java.io.File;
class GFG {
public static void main(String[] args)
{
File directory = new File( "/home/mayur" );
if (directory.isDirectory()) {
String arr[] = directory.list();
if (arr.length > 0 ) {
System.out.println( "The directory "
+ directory.getPath()
+ " is not Empty!" );
}
else {
System.out.println( "The directory "
+ directory.getPath()
+ " is Empty!" );
}
}
}
}
|
Output:

Method 2: Use of DirectoryStream
Java 7 onwards, the Files.newDirectoryStream method was introduced that returns a DirectoryStream<Path> to iterate over all the entries in the directory.
- Suppose there is a directory present in the path /home/user/folder and it has three text files.
- Create a boolean function that checks if the directory is empty or not
- If a given path is a file then throw an exception
- If a given directory has files, return false else true.
- Print the result
See the below program for the above approach.
Java
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
public class GFG {
public static boolean isEmptyDirectory(File directory)
throws IOException
{
if (directory.exists()) {
if (!directory.isDirectory()) {
throw new IllegalArgumentException(
"Expected directory, but was file: "
+ directory);
}
else {
try (DirectoryStream<Path> directoryStream
= Files.newDirectoryStream(
directory.toPath())) {
return !directoryStream.iterator()
.hasNext();
}
}
}
return true ;
}
public static void main(String[] args)
throws IOException
{
File directory = new File( "/home/mayur" );
if (isEmptyDirectory(directory)) {
System.out.println( "The directory "
+ directory.getPath()
+ " is Empty!" );
}
else {
System.out.println( "The directory "
+ directory.getPath()
+ " is Not Empty!" );
}
}
}
|
Output:
