Reading an ASCII file (BufferedReader)
by , 11-10-2011 at 05:14 PM (2111 Views)
Normally 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:
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.Java Code:String fileName = ""; System.out.println("Please enter the file name: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); fileName = br.readLine();
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.
Reading the file may raise following exceptions:Java Code: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(); }
FileNotFoundException
IOException
It is always a good idea to write separate catch blocks for known exceptions.









Email Blog Entry
sorry for all the questions
thanks...
06-14-2013, 02:22 PM in gbonecapone