Reading an ASCII file (BufferedReader)
2 November 2007Normally we give input to Java applications from command prompt or through GUI. But sometimes, when inputs are in bulk, we can use ASCII files for input. Such files must have some agreed upon pattern so Java parser can understand the meaning of the text. There are many ways to read a file but one of the simplest way is to use BufferedReader class which is found in java.io package.
First prompt the user to enter the file name with path. This can be done using:
String fileName = ""; System.out.println("Please enter the file name: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); fileName = br.readLine();
Now we have the file name in a string called fileName. Create a File object and pass the filename to it. This File object will be used later. We will use BufferedReader for reading the text file. BufferedReader is efficient for reading characters through character input stream. Buffer size can be specified but the default size is quite large to accomplish the normal tasks.
BufferedReader has two constructors. One with the buffer size and one without the buffer size. The default buffer size is 8192 characters.
When your BufferedReader object is initialized, you can use its readLine method to read the file line by line. You may parse lines as they are fetched and store only the lines that are required for further processing.
StringBuffer contents = new StringBuffer(); BufferedReader input = null; try { input = new BufferedReader( new FileReader(aFile),1 ); String line = null; //not declared within while loop while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty("line.separator")); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex){ ex.printStackTrace(); }
Reading the file may raise following exceptions:
FileNotFoundException
IOException
It is always a good idea to write separate catch blocks for known exceptions.
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Reading an ASCII file (BufferedReader)
Scanner is a nice class too because it uses fast NIO for files.
Scanner scanner = new Scanner( file );
while ( scanner.hasNextLine )
{
String line = scanner.nextLine();
…
}
scanner.close();
Hi man,
The: BufferedReader input = null;
should be closed in final:
final {
try{
input.close();
} catch (IOException e) {
// handle or rethrow
}
}