java-IO-回退流

回退流

在JAVA IO中所有的数据都是采用顺序的读取方式,即对于一个输入流来讲都是采用从头到尾的顺序读取的,如果在输入流中某个不需要的内容被读取进来,我们就要采取办法把不需要的数据处理掉,为了解决这样的处理问题,在JAVA中提供了一种回退输入流(PushbackInputStream、PushbackReader),可以把读取进来的某些数据重新回退到输入流的缓冲区之中。
回退流主要给我们提供了三种回退方法

  1. public void unread(int b)throws IOException//推回一个字节:将其复制到推回缓冲区之前。此方法返回后,要读取的下一个字节的值将为 (byte)b。
  2. public void unread(byte[] b) throws IOException //推回一个 byte 数组:将其复制到推回缓冲区之前。
  3. public void unread(byte[]b, int off, int len) throws IOException //推回 byte 数组的某一部分:将其复制到推回缓冲区之前

具体可以看一下示例:

 public static void main(String[] args) throws IOException {
        String s = "abcdefghj";
        ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes());//读取内存字符串
      PushbackInputStream pis = new PushbackInputStream(bais,4);//使用指定 size 的推回缓冲区创建 PushbackInputStream
        byte[]buffer = new byte[4];存放回退数据
       while ((pis.read(buffer))!=-1){
            System.out.println(new String(buffer));
            if (new String(buffer).equals("abcd")){
                pis.unread(buffer,2,2);回退buffer数组从2号位置后两位
                buffer = new byte[4];
            }
       }

输入结果
在这里插入图片描述

 public static void main(String[] args) throws IOException {
        String s = "abcdefghj";
          ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes());
        PushbackInputStream pis = new PushbackInputStream(bais,3);
        int n;
        byte[]buffer = new byte[3];
        while ((pis.read(buffer))!=-1){
            System.out.println(new String(buffer));
            if (new String(buffer).equals("abc")){
                pis.unread(new byte[]{'M','N','O'});//返回整个数组
                buffer = new byte[3];
            }
        }

结果:
在这里插入图片描述

   String s = "www.tulun.com";
        ByteArrayInputStream in = new ByteArrayInputStream(s.getBytes());
        PushbackInputStream pis = new PushbackInputStream(in);
        int n;
        while ((n=pis.read())!=-1){//读取内容
            if (n=='.'){//判断是否读到'.'
                pis.unread(n);
                pis.read();
                System.out.print(("(退回"+(char)n+")"));
            }else{
                System.out.print((char)n);
            }
        }

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值