【从零开始】推回输入流

在 输入/输出流体系中,有两个特殊的流

  1. PushbackInputStream
  2. PushbackReader

方法:

void unread(byte[]/char[] buf) : 将一个字节或者字符数组内容推回到推回缓冲区中,从而可以重复读取刚刚读的内容

void unread(byte[]/char[] buf, int off, int len) : 将一个字节或者字符数组里从 off 开始,长度为 len 字节/字符的内容推回到推回缓冲区中,从而可以重复读刚刚的内容

void unread(int b) : 将一个字节或者字符数组推回到推回缓冲区里,从而可以读取刚刚读的内容

这两个输入流都带有一个推回缓冲区,当程序调用这两个输入流的 unread() 方法时,系统会把指定数组的内容推回到推回缓冲区,当推回输入流每次调用read方法时,总是先读取推回缓冲区的内容,只有推回缓冲区的内容读完之后,才会从原始流中读取。

例如: 找出程序中 "hello world" 字符串,找到后打印其前边的内容

public class PushbackInputStreamTest{
	public static void main(String[] args){
		try(
		//指定推回缓冲区的长度为64
		PushbackInputstream ps = new PushbackInputStream(new FileReader("text.txt"),64))
		{
			char[] buf = new char[32];
			String lastContent = "";
			int hasRead= 0;
			while((hasRead = ps.read(buf)) >0){
				String content = new String(buf,0,hasRead);
				int index = 0;
				if((index=(lastContent+content).indexOf("hello world"))>0){
					ps.unread((lastContent+content).toCharArray()); // 将本次内容和上次的内容推回缓冲区
					if(index > 32){
						buf = new char[index];
					}
					ps.read(buf,0,index);
					System.out.print(new String(buf,0,index));
					System.exit(0);
				} else {
					System.out.print(lastContent);
					lastContent = content;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

转载于:https://my.oschina.net/whitejavadog/blog/2244996

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值