In this section we will discuss about the PushbackReader class in Java.
In this section we will discuss about the PushbackReader class in Java.In this section we will discuss about the PushbackReader class in Java.
PushbackReader is a class of java.io package that extends the java.io.FilterReader, reads the character streams. PushbackReader class provides the characters that they can be pushed back into the stream.
Constructor of PushbackReader
PushbackReader(Reader in) | This constructor is used to create a new PushbackReader which contains the
object of Reader (input stream). Syntax : public PushbackReader(Reader in) |
PushbackReader(Reader in, int size) | This constructor is used to create a new PushbackReader which contains the
object of Reader (input stream) as well as defined the specified size of buffer. Syntax : public PushbackReader(Reader in, int size) |
Methods detail
Example
Example of PushbackReader class is being given here which will demonstrate you how to use this class. In this example I have created a simple Java class named JavaPushbackReaderExample.java. In this example you will see that java.io.FileReader class is used this class reads the data of a file as character. Further I have used PushbackReader class and passed the object of FileReader (since FileReader extends the Reader so FileReader is a Reader) which will be treated as data source for the PushbackReader. Then read the data using the read() method.
Source Code
JavaPushbackReaderExample.java
import java.io.PushbackReader; import java.io.FileReader; import java.io.IOException; public class JavaPushbackReaderExample { public static void main(String args[]) { FileReader fr = null; PushbackReader pr = null; try { fr = new FileReader("test.txt"); pr = new PushbackReader(fr); int d; while((d = pr.read()) != -1) { System.out.print((char)d); } } catch(IOException ioe) { System.out.println(ioe); } finally { if(fr != null) { try { fr.close(); } catch(Exception e) { System.out.println(e); } } if(pr != null) { try { pr.close(); } catch(Exception e) { System.out.println(e); } } } } }
Output
When you will execute the above code you will get the output as follows :
Ads