Java Example – Traversing All Subdirectories Under a Specified Directory
The following example demonstrates how to use the list method of the File class to traverse all subdirectories under a specified directory:
Main.java File
import
java
.
io
.*;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
File
dir
=
new
File
(
"
F:
"
)
;
File
[
]
files
=
dir
.
listFiles
(
)
;
FileFilter
fileFilter
=
new
FileFilter
(
)
{
public
boolean
accept
(
File
file
)
{
return
file
.
isDirectory
(
)
;
}
}
;
files
=
dir
.
listFiles
(
fileFilter
)
;
System
.
out
.
println
(
files
.
length
)
;
if
(
files
.
length
==
0
)
{
System
.
out
.
println
(
"
The directory does not exist or it is not a directory
"
)
;
}
else
{
for
(
int
i
=
0
;
i
<
files
.
length
;
i
++
)
{
File
filename
=
files
[
i
]
;
System
.
out
.
println
(
filename
.
toString
(
)
)
;
}
}
}
}
The output of the above code is:
14
F:\C Drive Data Old HDD
F:\Desktop1
F:\harsh
F:\hharsh final
F:\hhhh
F:\mov
F:\msdownld.tmp
F:\New Folder
F:\ravi
F:\ravi3
F:\RECYCLER
F:\System Volume Information
F:\temp
F:\work
Java Examples