Friday, 10 July 2015

How to Read Text Files Line by Line Using BufferedReader in Java ?

  Using Buffered Reader class, you can read a text file line by line in java. Since text files contains character data, Buffered Reader is the best choice. All the Reader classes helps you to read character data.

Step by Step explanation:

1. In order to read the give file, first of all, you need to get the input stream object. For this, use FileInputStream class. You need to pass file path to the constructor of FileInputStream.
FileInputStream fis = new FileInputStream(filePath);

2. Once you got the FileInputStream object, then get the InputStreamReader object by passing the FileInputStream object to the InputStreamReader's constructor.
InputStreamReader isr = new InputStreamReader(fis); 

3. After the above step, now get the BufferedReader object by passing InputStreamReader object, which you have created before.
BufferedReader br = new BufferedReader(isr);

4. BufferedReader class has a method named readLine() which gives you a line one by one. The readLine() method returns either String or null. it returns null, if it reached end of the file. So until it returns null, we need to call the readLine() method inside a for loop. below is the code for that.
String line = null;

while((line = br.readLine()) != null) {

    System.out.println(line);

}

5. After reading entire file, you need to close the BufferedReader by calling it's close() method. Closing a BufferedReader also causes to close the underlying InputStream.
br.close();

The complete java program is below.
package com.speakingcs.files;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadTextFile {
 
 public static void main(String[] args) {
  
  ReadTextFile rtf = new ReadTextFile();
  
  try {
   rtf.readTextFile("C:\\Users\\sreenath\\Desktop\\sampletext.txt");
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  
  
 }

 private void readTextFile(String fileName) throws IOException {
  
  FileInputStream fis = null;
  InputStreamReader isr = null;
  BufferedReader br = null;
  
  try {
   fis = new FileInputStream(fileName);
   
   isr = new InputStreamReader(fis);
   
   br = new BufferedReader(isr);
   
   String str = null;
   while((str = br.readLine()) != null) {
    System.out.println(str);
   }
  } finally {
   if(fis != null) {
    fis.close();
   }
   
   if(isr != null) {
    isr.close();
   }
   
   if(br != null) {
    br.close();
   }
   
  }
 }

}



0 comments:

Post a Comment

Note: only a member of this blog may post a comment.