Programming Tutorials

PushbackReader sample program in Java

By: Daniel Malcolm in Java Tutorials on 2022-09-15  

PushbackReader is a class in Java that allows you to push back characters that you have already read back into the input stream so that they can be read again later. This class is often used with other input classes like BufferedReader and InputStreamReader. Here's an example program that demonstrates the use of PushbackReader:

import java.io.*;

public class PushbackReaderExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        char[] buf = new char[str.length()];
        str.getChars(0, str.length(), buf, 0);
        
        try (PushbackReader pr = new PushbackReader(new CharArrayReader(buf))) {
            int c;
            while ((c = pr.read()) != -1) {
                if (c == 'o') {
                    pr.unread(c);
                    c = pr.read();
                    System.out.print((char)c);
                } else {
                    System.out.print((char)c);
                }
            }
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

This program reads the string "Hello, World!" from a character array and creates a PushbackReader object to read from it. It then reads each character from the input stream, and if it encounters the character 'o', it pushes it back into the input stream using the unread() method. This causes the character 'o' to be read again on the next call to read(), which is then printed to the console.

Here are the constructors available in the PushbackReader class:

  1. PushbackReader(Reader in) Creates a new PushbackReader that reads from the given input stream.

  2. PushbackReader(Reader in, int size) Creates a new PushbackReader that reads from the given input stream, with a pushback buffer of the specified size. The size parameter must be non-negative.

Note that the pushback buffer can be specified as an optional parameter in the constructor. If not specified, a default size is used.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)