Site Navigation

Jul 28, 2011

Read a Text File Using JDK7

Duke WavingHere is a really simple example of how to read a text file using JDK7. The main new feature you will see is the try with resources block on line 10. The program just numbers the lines of a text files up to 9999 lines long.

LineNumber.java
   1 import java.io.BufferedReader;
   2 import java.io.FileNotFoundException;
   3 import java.io.FileReader;
   4 import java.io.IOException;
   5 
   6 public class LineNumber {
   7     public static void main(String[] args){
   8         String fileName = args[0];
   9     
  10         try(BufferedReader reader = new BufferedReader(new FileReader(fileName))){
  11             String line = ""; int c = 1;
  12             while((line = reader.readLine()) != null){
  13                 System.out.printf("%4d %s\n", c, line);
  14                 c++;
  15             }
  16             
  17         } catch (FileNotFoundException e) {
  18             e.printStackTrace();
  19         } catch (IOException e){
  20             e.printStackTrace();
  21         }
  22     }    
  23 }

Text Version of the Source Code
Post a Comment

Favorite Links Feed