Java Example – Checking Whether a Directory Is Empty
The following example demonstrates using the file.isDirectory() and file.list() methods of the File class to check whether a directory is empty:
Main.java File
import
java
.
io
.
File
;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
File
file
=
new
File
(
"
./testdir
"
)
;
//
The testdir directory under the current directory
if
(
file
.
isDirectory
(
)
)
{
if
(
file
.
list
(
)
.
length
0
)
{
System
.
out
.
println
(
"
The directory is not empty!
"
)
;
}
else
{
System
.
out
.
println
(
"
The directory is empty!
"
)
;
}
}
else
{
System
.
out
.
println
(
"
This is not a directory!
"
)
;
}
}
}
The output of the above code is:
目录 D://Java/file.txt 不为空!
Java Examples