跟我学IO(PushbackReader类)

PushbackReader类提供了将将字符推回到流的字符流Reader。你可以通过PushbackReader(Reader in, int size)构造方法来构造推回PushbackReader对象,size表示回推字符数组大小。

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.
沉浸于现实的忙碌之中,没有时间和精力思念过去,成功也就不会太远了。——雷音
0 不喜欢
说说我的看法 -
全部评论(
没有评论
目录
热门标签
热门文章
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号