文章来源:http://www.bug315.com/article/225.htm
PushbackReader类提供了将将字符推回到流的字符流Reader。你可以通过PushbackReader(Reader in, int size)构造方法来构造推回PushbackReader对象,size表示回推字符数组大小。
实例:读取document目录下面的reader01.txt文件,然后将读取的字符数组转换成字符串,查看字符串中是否存在指定的字符串。如果存在指定的字符串,则将本次读取的字符数组推回到输入字符流中,然后再将其读取出来,进行输出(在输出前后追加<<和>>)。
package io.reader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PushbackReader;
public class PushbackReaderTest {
public static void main(String[] args) {
PushbackReader reader = null;
try {
// 构建PushbackReader字符流对象
reader = new PushbackReader(
new InputStreamReader(
new FileInputStream("document/reader01.txt")), 64);
char[] buffer = new char[64];
int len = 0;
while ( (len = reader.read(buffer)) != -1 ) {
String tempStr = new String(buffer, 0, len);
System.out.println( tempStr );
// 判断本次读取的字符串中是否存在“you”字符串
if ( tempStr.indexOf("you") != -1 ) {
// 将本次读取的字符数组推回到输入字符流
reader.unread(tempStr.toCharArray());
// 读取推回的字符流,然后输出
if ( (len = reader.read(buffer)) != -1 ) {
System.out.println("<<" + new String(buffer, 0, len) + ">>");
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if ( null != reader ) {
try {
reader.close();
reader = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
输出结果:
It’s not my way to love you just when no one’s looking.
It’s no
<<It’s not my way to love you just when no one’s looking.
It’s no>>
t my way to take your hand if I’m not sure.
It’s not my way to
<<t my way to take your hand if I’m not sure.
It’s not my way to >>
let you see what’s going on inside of me.
When it’s a love you’
<<let you see what’s going on inside of me.
When it’s a love you’>>
ll not be needing you’re not free.
Please stop pulling at my sl
<<ll not be needing you’re not free.
Please stop pulling at my sl>>
eeve if you’re just playing.
If you’ll not take the things you
<<eeve if you’re just playing.
If you’ll not take the things you >>
make me want to give.