Java -- Reading a File
This sample Java class demonstrates how to read a simple text file
one line at a time. First, open a FileReader
, then filter this through a BufferedReader
to read the file one line at a time. Detailed comments are included with the code below.
ReadFile.java
1:import java.io.*; 2: 3:public class ReadFile{ 4: public static void main(String[] args){ 5: try { 6: 7: /* Sets up a file reader to read the file passed on the command 8: line one character at a time */ 9: FileReader input = new FileReader(args[0]); 10: 11: /* Filter FileReader through a Buffered read to read a line at a 12: time */ 13: BufferedReader bufRead = new BufferedReader(input); 14: 15: String line; // String that holds current file line 16: int count = 0; // Line number of count 17: 18: // Read first line 19: line = bufRead.readLine(); 20: count++; 21: 22: // Read through file one line at time. Print line # and line 23: while (line != null){ 24: System.out.println(count+": "+line); 25: line = bufRead.readLine(); 26: count++; 27: } 28: 29: bufRead.close(); 30: 31: }catch (ArrayIndexOutOfBoundsException e){ 32: /* If no file was passed on the command line, this expception is 33: generated. A message indicating how to the class should be 34: called is displayed */ 35: System.out.println("Usage: java ReadFile filename\n"); 36: 37: }catch (IOException e){ 38: // If another exception is generated, print a stack trace 39: e.printStackTrace(); 40: } 41: 42: }// end main 43:}
Here is sample output from running the program.
C:> java ReadFile Temp.java 1: import java.lang.*; 2: 3: class Temp{ 4: public static void main(String[] args) { 5: System.out.println("This is a template file"); 6: } 7: } C:> java ReadFile Usage: java ReadFile filename