Java - PushbackInputStream example

Posted on November 6, 2016


A PushbackInputStream adds functionality to another input stream to pushback or unread one byte. The read() method of the PushbackInputStream class reads one byte from input stream ,whereas the unread() method pushes back one byte to the input stream.

Here is an example to demonstrate this.

PushbackInputStreamExample.java

package com.boraji.tutorial.io;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;

/**
 * @author imssbora
 */
public class PushbackInputStreamExample {
	public static void main(String[] args) {
		String data = "This an example of PushbackInputStream";

		ByteArrayInputStream byteArrayInputStream = null;
		PushbackInputStream pushbackInputStream = null;
		try {
			byteArrayInputStream = new ByteArrayInputStream(data.getBytes());
			pushbackInputStream = new PushbackInputStream(byteArrayInputStream);
			
			//Read first character from stream
			int i=pushbackInputStream.read();
			System.out.println((char)i);
			
			//Push back first character to stream
			pushbackInputStream.unread(i);
			
			//Now Read full bytes
			byte b[] = new byte[data.getBytes().length];
			pushbackInputStream.read(b);
			System.out.println(new String(b));

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

		}
	}
}

Output

T
This an example of PushbackInputStream