Java PushbackReader Example

The PushbackReader is useful when you parse data from a Reader. Sometimes you would have the requirement to read ahead a few characters to see what is coming next, before you can determine how to interprete the current character. The PushbackReader allows that facility for the programmers. This class defines two constructors.

  • PushbackReader(Reader in) – Creates a new pushback reader with a one-character pushback buffer.
  • PushbackReader(Reader in, int size) – Creates a new pushback reader with a pushback buffer of the given size.

Lets look at the example to understand how to use PushbackReader while reading a file.

PushBackReaderExample.java

package javabeat.net.core;

import java.io.FileReader;
import java.io.IOException;
import java.io.PushbackReader;

/**
 * Java StringReader Example
 *
 * @author Krishna
 *
 */
public class PushBackReaderExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws IOException {
		//Create Reader instance
		FileReader reader = new FileReader("TextFile.txt");

		//Create PushBackReader instance with setting 10 as unread
		PushbackReader pushbackReader = new PushbackReader(reader,10);
		int c = pushbackReader.read();
		while (c != -1){
			//Converting to character
			System.out.print((char)c);
			c= pushbackReader.read();
		}
		//Closing the file io
		reader.close();

	}

}

TextFile.txt

India
United Kingdom
Australia
Singapore

Output…

India
United Kingdom
Australia
Singapore

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*