PushBackReader Demo

This post explains PushBackReader class in java. This reader allows us to put the data read from the input stream back into the stream and reread it again. The below explains how to use it

Main Class

package IO;

import java.io.PushbackReader;
import java.io.StringReader;

public class PushBackReaderDemo {
    public static void main(String[] args) throws Exception {
        try(StringReader sr = new StringReader("Hello, welcome to PushBackReader demo.");
        PushbackReader pbr = new PushbackReader(sr);) {
            for(int ch = pbr.read(), i = 0; ch != -1; i++, ch = pbr.read()) {
                if(i == 10) {


Hello, welccome to PushBackReader demo.


The code read characters one by one and when 10th character (which is ‘c’ in this case) is read, it is displayed and added back into the input stream by calling the below method


And then read again displaying ‘c’ twice in output.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s