Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Example – Traversing All Files Under a Specified Directory

Java Example – Traversing All Files Under a Specified Directory

Java Examples Java Examples

The following example demonstrates how to use the list method of the File class to output all files under a specified directory:

Main.java File

import

java

.

io

.

File

;

class

Main

{

public

static

void

main

(

String

[

]

args

)

{

File

dir

=

new

File

(

"

C:

"

)

;

String

[

]

children

=

dir

.

list

(

)

;

if

(

children

==

null

)

{

System

.

out

.

println

(

"

The directory does not exist or it is not a directory

"

)

;

}

else

{

for

(

int

i

=

0

;

i

<

children

.

length

;

i

++

)

{

String

filename

=

children

[

i

]

;

System

.

out

.

println

(

filename

)

;

}

}

}

}

The output of the above code is:


build
build.xml
destnfile
detnfile
filename
manifest.mf
nbproject
outfilename
src
srcfile
test

Java Examples Java Examples