1. 程式人生 > >InputStream中mark方法readlimit引數詳解

InputStream中mark方法readlimit引數詳解

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。