Thursday, July 28, 2022

Java BufferedReader Class With Examples

Java BufferedReader class is used to read text from a character-input stream. This class is used as a wrapper around any Reader (FileReader and InputStreamReader) whose read() operations may be costly. BufferedReader as the name suggests buffers characters so as to provide for the efficient reading of characters, arrays, and lines. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

Java BufferedReader constructors

  • BufferedReader(Reader in)- Wraps the passed Reader and creates a buffering character-input stream that uses a default-sized input buffer. Default buffer size for BufferedReader is 8192 bytes i.e. 8 KB. For example, creating BufferedReader instance by wrapping an instance of FileReader-
        // Instance of FileReader wrapped in a BufferedReader
        BufferedReader br = new BufferedReader(new FileReader("resources/abc.txt"));
     
  • BufferedReader(Reader in, int sz)- Wraps the passed Reader and creates a buffering character-input stream that uses an input buffer of the specified size.

Java BufferedReader methods

Some of the most used methods in BufferedReader class are as given below-

  • read()- Reads a single character. Returns the character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached.
  • read(char[] cbuf, int off, int len)- Reads characters into a portion of an array.
  • readLine()- Reads a line of text.
  • ready()- Tells whether this stream is ready to be read.
  • skip(long n)- Skips characters.
  • lines()- Returns a Stream, the elements of which are lines read from this BufferedReader. The Stream is lazily populated, i.e., read only occurs during the terminal stream operation.

Java BufferedReader examples

For using BufferedReader steps are as follows-

  1. Create an instance of BufferedReader wrapped around another Reader.
  2. Using that instance read file.
  3. Close the stream, you should close the resources in finally block or you can use try-with-resources to automatically manage resources.

1. Using read() method of the Java BufferedReader class to read file character by character.

public class BRExample {

 public static void main(String[] args) {
  BufferedReader br = null;
  try{
   // Instance of FileReader wrapped in a BufferedReader
   br = new BufferedReader(new FileReader("F:\\NETJS\\Test\\abc.txt"));
   // Read chars from the file, returns -1 when end of stream is reached
   int i;
   while((i = br.read()) != -1){
    char ch = (char)i;
       System.out.println("char is - " + ch);
   }
  }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) {  
    e.printStackTrace();
   }
  }
 }
}

2. Reading characters into a portion of an array using read(char[] cbuf, int off, int len) method of the Java BufferedReader class. Here off represents Offset at which to start storing characters and len represents maximum number of characters to read.

public class BRExample {

 public static void main(String[] args) {
  try(BufferedReader br = new BufferedReader(new FileReader("F:\\NETJS\\Test\\abc.txt"))){
   // char buffer where characters are read
   char[] chArray = new char[10];
   
   br.read(chArray, 0, chArray.length);
   for(char c : chArray) {
    System.out.println(c);
   }

  }catch(IOException ioExp){
   System.out.println("Error while reading file " + ioExp.getMessage());
  }
 }
}

3. Reading a line of text using readLine() method of the BufferedReader class in Java.

public class BRExample {

 public static void main(String[] args) {
  BufferedReader br = null;
  try{
   String strLine;
   // Instance of FileReader wrapped in a BufferedReader
   br = new BufferedReader(new FileReader("F:\\NETJS\\Test\\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) {  
    e.printStackTrace();
   }
  }
 }
}

4. Reading from file after skipping few characters using skip() method of the Java BufferedReader class. Code also checks whether stream is ready or not.

public class BRExample {

 public static void main(String[] args) {
  BufferedReader br = null;
  try{
   String strLine;
   // Instance of FileReader wrapped in a BufferedReader
   br = new BufferedReader(new FileReader("F:\\NETJS\\Test\\abc.txt"));
   if(br.ready()) {
    br.skip(10);
    // 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) {  
    e.printStackTrace();
   }
  }
 }
}

5. Using lines() method of the Java BufferedReader class, which is available Java 8 onward, to get a Stream. Using filter method of the Java Stream API to filter lines which contain the given String and print those lines.

public class BRExample {
  public static void main(String[] args) {
    BufferedReader br = null;
    try{
      // Instance of FileReader wrapped in a BufferedReader
      br = new BufferedReader(new FileReader("F:\\NETJS\\Test\\abc.txt"));
      Stream<String> stream = br.lines();
      stream.filter(line -> line.contains("BufferedReader")).forEach(System.out::println);
    }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) {        
        e.printStackTrace();
      }
    }
  }
}

That's all for this topic Java BufferedReader Class With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. getPath(), getCanonicalPath() and getAbsolutePath() Methods in Java
  2. Write to a File in Java
  3. Reading File in Java Using Files.lines And Files.newBufferedReader
  4. How to Read Excel File in Java Using Apache POI
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. Java Program to Delete a Node From Binary Search Tree (BST)
  2. CallableStatement Interface in Java-JDBC
  3. CountDownLatch in Java Concurrency
  4. Java join() Method - Joining Strings
  5. Why no Multiple Inheritance in Java
  6. Dependency Injection in Spring Framework
  7. Spring Web Reactive Framework - Spring WebFlux Tutorial
  8. Global Keyword in Python With Examples

No comments:

Post a Comment