Java InputStream.mark()设置输入流的当前位置

定义

public void mark(int readlimit)
参数

readlimit - 可读取的最大字节数。

返回

不返回任何值

异常

IOException:I/O 错误

实例

public static void main(String[] args) throws Exception
{
    InputStream is = null;
    try
    {
        is = new FileInputStream("C://51gjie.txt");
        System.out.println("Char : " + (char) is.read());
        is.mark(0);//设置流位置重新为0
        System.out.println("Char : " + (char) is.read());
        if(is.markSupported())
        {
            is.reset();
            System.out.println("Char : " + (char) is.read());
        }
    }
    catch(Exception e)
    {}
    finally
    {
        if(is != null) is.close();
    }
}

1. InputStream的mark方法不执行任何操作,只是标记输入流的位置,如果要重新定位到这个位置,需要调用reset()方法才行。

2. 如果方法markSupported返回true,则流将以某种方式记住在调用mark之后读取的所有字节,并准备在每次调用方法reset时再次提供相同的字节。 但是,如果在调用复位之前从流中读取了超过readlimit个字节的数据,则该流根本不需要记住任何数据。