Showing posts with label code snippet. Show all posts
Showing posts with label code snippet. Show all posts

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() );
}
}

How to write a File in Java

Code snippet on how to write a File in Java

Note: myFile.txt - file to be written

Java Imports:
java.io.BufferedWriter,
java.io.FileWriter,
java.io.IOException

Code Snippet:
try {
// myFile.txt - file to write
FileWriter fileWriter = new FileWriter( "myFile.txt" );
BufferedWriter bufferedWriter = new BufferedWriter( fileWriter );
// write to a file line 0, line 1, line n
for( int index = 0; index < 10; index++ ) {
bufferedWriter.write( "line " +index+ "\n" );
}
// close writer
bufferedWriter.close();
} catch ( IOException ioe ) {
// handle exception
}

How to read a File in Java

Code snippet on how to read a file in Java

Note: myFile.txt - file that will be read

Java Imports:
java.io.BufferedReader,
java.io.File,
java.io.FileReader,
java.io.IOException


Code Snippet:
try {
// myFile.txt - text file to read
File file = new File( "myFile.txt" );
FileReader fileReader = new FileReader( file );
BufferedReader bufferedReader = new BufferedReader( fileReader );
String line;
// line - holder for the line of text
while( ( line = bufferedReader.readLine() ) != null ) {
System.out.println( line ); // prints the text per line on console
}
// don't forget to dispose after use
fileReader.close();
bufferedReader.close();
} catch ( IOException ioe ) {
// handle exception
}
Google