java.io中的mark与reset

来源:互联网 发布:淘宝买家如何取消介入 编辑:程序博客网 时间:2024/06/08 04:26
在开发中有这样的一个需求, 在一个流读完后,还想再次使用该流。
这时候就可以通过将输入流中的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();   
        }   
    } 
原创粉丝点击