
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a Directory Is Not Empty in Java
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
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"); } }