InputStream中mark方法readlimit参数详解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014248473/article/details/86062694

InputStream中mark方法readlimit参数详解

mark(int readlimit);

网上给出的解释:
/***************************************************************/
readlimit 参数给出当前输入流在标记位置变为非法前允许读取的字节数。

比如说mark(10),那么在read()10个以内的字符时,reset()操作后可以重新读取已经读出的数据,
如果已经读取的数据超过10个,那reset()操作后,就不能正确读取以前的数据了,
因为此时mark标记已经失效。  
/***************************************************************/
但实际测试结果却不尽然。看下面的测试:

使用 ByteArrayInputStream 测试

byte[] byteArr = {1, 2, 3, 4, 5};
try(
    InputStream in = new ByteArrayInputStream(byteArr)
) {
    in.mark(1);
    
    in.read();
    in.reset();
    
    in.read();
    in.read();
    in.reset();
    
    in.read();
    in.read();
    in.read();
    in.reset();
    
    System.out.println("reset success");
}catch (IOException e){
    e.printStackTrace();
}

将readlimit设为1,但是读取超过1依然可以reset成功!

使用 BufferedInputStream 测试

byte[] byteArr = {1, 2, 3, 4, 5};
try(
    InputStream in = new ByteArrayInputStream(byteArr);
    BufferedInputStream is = new BufferedInputStream(in,2)
) {
    is.mark(1);
    
    is.read();
    is.reset();
    System.out.println("reset success");
    
    is.read();
    is.read();
    is.reset();
    System.out.println("reset success");
    
    is.read();
    is.read();
    is.read();
    is.reset();
    System.out.println("reset success");
    
}catch (IOException e){
    e.printStackTrace();
}

//输出结果如下:
reset success
reset success
java.io.IOException: Resetting to invalid mark
...

上面readlimit设为1,缓冲池大小设为2,结果读取个数大于2的时候mark标记失效。

结论是:当readlimit小于缓冲池大小时,那么mark标记失效前允许读取的个数为缓冲池大小。

byte[] byteArr = {1, 2, 3, 4, 5};
try(
    InputStream in = new ByteArrayInputStream(byteArr);
    BufferedInputStream is = new BufferedInputStream(in,2)
) {
    is.mark(3);
    
    is.read();
    is.reset();
    System.out.println("reset success");
    
    is.read();
    is.read();
    is.reset();
    System.out.println("reset success");
    
    is.read();
    is.read();
    is.read();
    is.reset();
    System.out.println("reset success");
    
    is.read();
    is.read();
    is.read();
    is.read();
    is.reset();
    System.out.println("reset success");
    
}catch (IOException e){
    e.printStackTrace();
}

//输出结果如下:
reset success
reset success
reset success
java.io.IOException: Resetting to invalid mark
...

上面readlimit设为3,缓冲池大小设为2,结果读取个数大于3的时候mark标记失效。

结论是:当readlimit大于缓冲池大小时,那么mark标记失效前允许读取的个数为readlimit。

猜你喜欢

转载自blog.csdn.net/u014248473/article/details/86062694
今日推荐