[j2se]java.io中的mark与reset

java.io中的mark与reset
 
在开发中有这样的一个需求, 在一个流读完后,还想再次使用该流。
这时候就可以通过将输入流中的mark()与reset()方法结合使用来达到该效果。
但不是所有的流都可以使用mark()和reset()方法. 否则使用的时候会抛出mark/reset not supported 异常。
可以通过markSupported()方法来判断该输入流是否支持mark()与reset()方法。(一般缓冲流才支持该方法)。
 
        InputStream in = 
                new FileInputStream("redis.properties");
        InputStream in1 = 
                ReReadStream.class.getClassLoader().getResourceAsStream("e.txt");
        BufferedInputStream bis = new BufferedInputStream(in);
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(isr);
        System.out.println(in.markSupported());  //false 
        System.out.println(bis.markSupported()); //true
        System.out.println(isr.markSupported()); //false
        System.out.println(br.markSupported());  //true
        System.out.println(in1.markSupported());  //true 
 
比较诡异的地方是按照FileInputStream读取到的流不支持mark,reset操作, 而getResourceAsStream方式读取到的流是支持mark,reset操作的。
而且支持mark,reset的缓冲流如果在mark过后进行读取的字节长度超过缓冲区的长度后,会抛出mark/reset not supported异常。
 
        public static void main(String[] args) {   
        try {   
            // 初始化一个字节数组,内有5个字节的数据   
            byte[] bytes={1,2,3,4,5};   
            // 用一个ByteArrayInputStream来读取这个字节数组   
            ByteArrayInputStream in=new ByteArrayInputStream(bytes);   
            // 将ByteArrayInputStream包含在一个BufferedInputStream,并初始化缓冲区大小为2。   
            BufferedInputStream bis=new BufferedInputStream(in,2);
            // 做一个书签
            bis.mark(1);   
            // 读取两个字节   
            System.out.println(bis.read()+","+bis.read()); //1,2
            //reset操作
            bis.reset();
            // 连续读取三个字节,超过了缓冲区大小,mark标记失效
            System.out.println(bis.read()+","+bis.read()+","+bis.read()); //1,2,3
            // 抛出异常(Resetting to invalid mark)
            bis.reset();
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
    } 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值