Java Example – Deleting a Directory
The following example demonstrates using the ofdir.isDirectory(), dir.list(), and deleteDir() methods of the File class to delete a directory after deleting its files one by one:
Main.java File
import
java
.
io
.
File
;
public
class
Main
{
public
static
void
main
(
String
[
]
argv
)
throws
Exception
{
//
Delete the test directory under the current directory
deleteDir
(
new
File
(
"
./test
"
)
)
;
}
public
static
boolean
deleteDir
(
File
dir
)
{
if
(
dir
.
isDirectory
(
)
)
{
String
[
]
children
=
dir
.
list
(
)
;
for
(
int
i
=
0
;
i
<
children
.
length
;
i
++
)
{
boolean
success
=
deleteDir
(
new
File
(
dir
,
children
[
i
]
)
)
;
if
(
!
success
)
{
return
false
;
}
}
}
if
(
dir
.
delete
(
)
)
{
System
.
out
.
println
(
"
The directory has been deleted!
"
)
;
return
true
;
}
else
{
System
.
out
.
println
(
"
Failed to delete the directory!
"
)
;
return
false
;
}
}
}
The output of the above code is:
目录已被删除!
Java Examples