Thursday, October 18, 2007

How to read what inside a directory in Java

Code Snippet on reading files and folders inside a directory in Java

Java Imports:
java.io.File

Code Snippet:
File directory = new File( "C:/" );
File[] fileList = directory.listFiles();

// Iterate through the fileList
for( int index = 0; index < fileList.length; index++ ) {
if( fileList[ index ].isFile() ) {
// prints the file names
System.out.println( "File Name " +fileList[ index ].getName() );
} else if( fileList[ index ].isDirectory() ) {
// prints the directory names
System.out.println( "Directory Name: " +fileList[ index ].getName() );
}
}

No comments:

Google