This post explains PushBackReader class in java. This reader allows us to put the data read from the input stream back into the stream and reread it again. The below explains how to use it
Main Class
package IO;
import java.io.PushbackReader;
import java.io.StringReader;
public class PushBackReaderDemo {
public static void main(String[] args) throws Exception {
try(StringReader sr = new StringReader("Hello, welcome to PushBackReader demo.");
PushbackReader pbr = new PushbackReader(sr);) {
for(int ch = pbr.read(), i = 0; ch != -1; i++, ch = pbr.read()) {
System.out.print((char)ch);
if(i == 10) {
pbr.unread(ch);
}
}
}
}
}
Output
Hello, welccome to PushBackReader demo.
Explanation
The code read characters one by one and when 10th character (which is ‘c’ in this case) is read, it is displayed and added back into the input stream by calling the below method
pbr.unread(ch);
And then read again displaying ‘c’ twice in output.