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

Java Example – Finding Files in a Specified Directory

Java Example – Finding Files in a Specified Directory

Java Examples Java Examples

The following example demonstrates using the dir.list() method of the File class to find the list of all files in a specified directory:

Main.java File

import

java

.

io

.

File

;

public

class

Main

{

public

static

void

main

(

String

[

]

argv

)

throws

Exception

{

File

dir

=

new

File

(

"

../java

"

)

;

String

[

]

children

=

dir

.

list

(

)

;

if

(

children

==

null

)

{

System

.

out

.

println

(

"

The directory does not exist

"

)

;

}

else

{

for

(

int

i

=

0

;

i

<

children

.

length

;

i

++

)

{

String

filename

=

children

[

i

]

;

System

.

out

.

println

(

filename

)

;

}

}

}

}

The output of the above code is:



Car.class

FileUtil.class

FileUtil.java

HelloWorld.class

HelloWorld.java

HelloWorldDebug.class

HelloWorldDebug.java

……

Java Examples Java Examples