Wednesday, 11 May 2016

Reading file in Java using BufferedReader

Java NIO and Java 8 provide many new ways to read a file in Java, like using Scanner to read file in Java, but BufferedReader still remains one of the most used way to read a file.

The advantage of using buffered I/O streams is that; in case of Buffered input streams data is read from a memory area known as a buffer; the native input API is called only when the buffer is empty. In case of buffered output streams data is written to a buffer, and the native output API is called only when the buffer is full. That way program is more efficient as each request doesn't trigger disk access or network activity.

Java code

import java.io.BufferedReader;
import java.io.IOException;

public class FileRead {

 public static void main(String[] args) {
  BufferedReader br = null;
  try{
   String strLine;
   // Instance of FileReader wrapped in a BufferedReader
   br = new BufferedReader(new java.io.FileReader("F:\\abc.txt"));
   
   // Read lines from the file, returns null when end of stream 
   // is reached
   while((strLine = br.readLine()) != null){
    System.out.println("Line is - " + strLine);
   }
  }catch(IOException ioExp){
   System.out.println("Error while reading file " + ioExp.getMessage());
  }finally {
   try {
    // Close the stream
    if(br != null){
     br.close();
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}

Output

Line is - This is a test file.
Line is - BuferedReader is used to read this file.

Using try-with-resources

If you are using Java 7 or above you can use try-with-resources for automatic resource management. In that case you don't have to explicitly close the resources. Resources (in this case stream) will be closed automatically after the program is finished with it.

Resource will be declared with the try statement itself when using try-with-resources.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileRead {

 public static void main(String[] args) {
  
  try(BufferedReader br  = new BufferedReader(new FileReader("F://abc.txt"))){
   String strLine;
   // Read lines from the file, returns null when end of stream 
   // is reached
   while((strLine = br.readLine()) != null){
    System.out.println("Line is - " + strLine);
   }
  }catch(IOException ioExp){
   System.out.println("Error while reading file " + ioExp.getMessage());
  }
 }
}

That's all for this topic Reading file in Java using BufferedReader. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to create PDF from XML using Apache FOP
  2. How to read file from the last line in Java
  3. Count total number of times each character appears in a String
  4. How to sort arraylist of custom objects in Java
  5. Lambda Expression Runnable example

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment