Java - PushbackReader example

Posted on November 9, 2016


PushbackReader is a character-stream reader that allows one or more characters to be pushed back into the stream.

Here is an example of PushbackReader class.

PushbackReaderExample.java

package com.boraji.tutorial.io;

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

/**
 * @author imssbora
 */
public class PushbackReaderExample {
	public static void main(String[] args) {
		String input = "This is an example of PushbackReader.";
		StringReader stringReader = null;
		PushbackReader pushbackReader = null;
		try {
			stringReader = new StringReader(input);
			pushbackReader = new PushbackReader(stringReader, 20);

			// Read first character
			int ch = pushbackReader.read();
			System.out.println((char) ch);

			// Push back first character
			pushbackReader.unread(ch);

			char[] c = new char[4];
			// Get first four characters
			pushbackReader.read(c);
			System.out.println(new String(c));

			// Push back first four characters
			pushbackReader.unread(c, 0, 4);

			// Read all characters
			c = new char[input.length()];
			pushbackReader.read(c);
			System.out.println(new String(c, 0, input.length()));

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (pushbackReader != null) {
					pushbackReader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Output

T
This
This is an example of PushbackReader.