Loading

Pages

Wednesday, February 20, 2013

How To Print Contents Of A File In Java

The following program shows how to use FileInputStream and BufferedReader to print contents of a file in Java.

 import java.io.BufferedReader;  
 import java.io.FileInputStream;  
 import java.io.FileNotFoundException;  
 import java.io.IOException;  
 import java.io.InputStreamReader;  
 public class PrintContents {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           BufferedReader br = null;  
           String str = null;  
           try {  
                br = new BufferedReader(new InputStreamReader(new FileInputStream(  
                          "C://abc/cde.txt")));  
                while ((str = br.readLine()) != null) {  
                     System.out.println(str);  
                }  
           } catch (FileNotFoundException e) {  
                e.printStackTrace();  
           } catch (IOException e) {  
                e.printStackTrace();  
           } finally {  
                try {  
                     if (br != null) {  
                          br.close();  
                     }  
                } catch (Exception e) {  
                     e.printStackTrace();  
                }  
           }  
      }  
 }  

No comments: