Java BufferedReader With Examples

Java-BufferedReader

Java BufferedReader class is a part of java.io package.

BufferedReader is a sub class of java.io.Reader class.

Java BufferedReader

  • BufferedReader reads text from a character –input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
  • The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
  • Compared to FileReader, BufferedReader read relatively large chunks of data from a file at once and keep this data in a buffer. When you ask for the next character or line of data, it is retrieved from the buffer, which reduces the number of times that time-intensive, file-read operations are performed.
  • In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReader and InputStreamReader. For example;
    
    BufferedReader in = new BufferedReader(new FileReader("file.txt"));
    Java-BufferedReader (1)
    

     

    Above code will buffer the input from the specified file. 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

  1. BufferedReader(Reader in): Creates a buffering character-input stream that uses a default-sized input buffer with specified Reader object.
  2. BufferedReader(Reader in, int sz): Creates a buffering character-input stream that uses an input buffer of the specified size with specified Reader object.

Java BufferedReader Example

Let’s have a look at important methods of BufferedReader class.

  1. read(): This method reads a single character and it returns the character as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached.
    
    package com.journaldev.examples;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    /**
     * Java Read file using BufferedReader Read method
     *
     * @author pankaj
     *
     */
    public class BufferedReaderReadExample {
    	public static void main(String[] args) {
    		BufferedReader bufferedReader = null;
    		FileReader fileReader = null;
    		try {
    			fileReader = new FileReader("D:/data/file.txt");
    			bufferedReader = new BufferedReader(fileReader);
    			int val = 0;
    			while ((val = bufferedReader.read()) != -1) {
    				char c = (char) val;
    				//prints the character
    				System.out.print(c);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally {
    			if (fileReader != null) {
    				try {
    					fileReader.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			if (bufferedReader != null) {
    				try {
    					bufferedReader.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    }
    

    BufferedReader implements AutoCloseable interface, hence we can use try with resource while using BufferedReader class.

    Let’s have look at the below example program.

    
    package com.journaldev.examples;
    import java.io.BufferedReader;
    import java.io.FileReader;
    /**
     * Java Read file using BufferedReader Read method using try with resource
     *
     * @author pankaj
     *
     */
    public class BufferedReaderReadTrywithResource {
    	public static void main(String[] args) {
    		try (BufferedReader bufferedReader = new BufferedReader(new FileReader("D:/data/file.txt"))){
    			int val = 0;
    			while ((val = bufferedReader.read()) != -1) {
    				char c = (char) val;
    				//prints the character
    				System.out.print(c);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    
  2. read(char[] cbuf, int off, int len): This methods reads character into specified array. It attempts to read as many characters as possible by repeatedly invoking the read method of the underlying stream. This iterated read continues until one of the following conditions becomes true:
    1. The specified number of characters have been read
    2. The read() method of the underlying stream returns -1, indicating end-of-file
    3. The ready() method of the underlying stream returns false, indicating that further input requests would block.

    If the first read on the underlying stream returns -1 to indicate end-of-file then this method returns -1. Otherwise this method returns the number of characters actually read.

    
    package com.journaldev.examples;
    import java.io.BufferedReader;
    import java.io.FileReader;
    /**
     * Java Read file using BufferedReader read(char[] cbuf, int off, int len) method
     *
     * @author pankaj
     *
     */
    public class BufferedReaderReadUsingArray {
    	public static void main(String[] args) {
    		try (BufferedReader bufferedReader = new BufferedReader(new FileReader("D:/data/file.txt"))){
    			char[] array = new char[10];
    			//read into array
    			bufferedReader.read(array, 0, 5);
    			for (char c : array) {
    				 // if char is empty
    	            if(c == (char)0) {
    	               c="*";
    	            }
    	            // prints characters
    	            System.out.print(c);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    
  3. readLine(): This method reads a line of text. A line is considered to be terminated by any one of a line feed (‘n’), a carriage return (‘r’), or a carriage return followed immediately by a line feed and it returns a String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.
    
    package com.journaldev.examples;
    import java.io.BufferedReader;
    import java.io.FileReader;
    /**
     * Java Read file using BufferedReader readLine() method
     *
     * @author pankaj
     *
     */
    public class BufferedReaderReadLineExample {
    	public static void main(String[] args) {
    		String line = null;
    		try (BufferedReader bufferedReader = new BufferedReader(new FileReader("D:/data/file.txt"))){
    			while ((line = bufferedReader.readLine()) != null) {
    				System.out.println(line);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    
  4. ready(): This method checks whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready and it returns true if the next read() is guaranteed not to block for input else returns false. Note that returning false does not guarantee that the next read will block.
    
    package com.journaldev.examples;
    import java.io.BufferedReader;
    import java.io.FileReader;
    /**
     * Java Read file using BufferedReader ready method
     *
     * @author pankaj
     *
     */
    public class BufferedReaderReadyExample {
    	public static void main(String[] args) {
    		try (BufferedReader bufferedReader = new BufferedReader(new FileReader("D:/data/file.txt"))){
    			//check of ready
    			if (bufferedReader.ready()) {
    				int val = 0;
    				while ((val = bufferedReader.read()) != -1) {
    					char c = (char) val;
    					//prints the character
    					System.out.print(c);
    				}
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    
  5. skip(long n): This method skips the specified number character and returns the number of character actually skipped. It will throw an IllegalArgumentException if n is negative.
    
    package com.journaldev.examples;
    import java.io.BufferedReader;
    import java.io.FileReader;
    /**
     * Java Read file using BufferedReader skip method
     *
     * @author pankaj
     *
     */
    public class BufferedReaderSkipExample {
    	public static void main(String[] args) {
    		try (BufferedReader bufferedReader = new BufferedReader(new FileReader("D:/data/file.txt"))) {
    			// skip 5 character
    			bufferedReader.skip(5);
    			System.out.println(bufferedReader.readLine());
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    Also check java read text file for more about how to read text file in java.

BufferedReader vs Scanner

  1. BufferedReader is synchronized while the Scanner is not.
  2. BufferedReader has big sized (8KB byte buffer) buffer while Scanner has small (1KB char buffer) buffer.
  3. BufferedReader is faster compared to Scanner.
  4. Scanner parses the token from contents of the stream while BufferedReader only reads the stream.

That’s all for Java BufferedReader, I hope nothing important got missed here.

Reference: Java doc

By admin

Leave a Reply

%d bloggers like this: