Thursday, October 18, 2007

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
}

No comments:

Google