Java BufferedInputStream mark()方法

java.io.BufferedInputStream.mark(int) 方法通过设置int值的字节之前,标记现在的位置为无效读取。

1 语法

public void mark(int readlimit)

2 参数

readLimit:标记位置无效之前要读取的字节数。

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.BufferedInputStream.mark(int)方法的例子
 */
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Demo {
    public static void main(String[] args) throws Exception {
        InputStream iStream = null;
        BufferedInputStream bis = null;

        try {
            // read from file d:/test.txt to input stream
            iStream = new FileInputStream("d:/test.txt");

            // input stream converted to buffered input stream
            bis = new BufferedInputStream(iStream);

            // read and print characters one by one
            System.out.println("Char : "+(char)bis.read());
            System.out.println("Char : "+(char)bis.read());
            System.out.println("Char : "+(char)bis.read());

            // mark is set on the input stream
            bis.mark(0);
            System.out.println("Char : "+(char)bis.read());
            System.out.println("reset() invoked");

            // reset is called
            bis.reset();

            // read and print characters
            System.out.println("char : "+(char)bis.read());
            System.out.println("char : "+(char)bis.read());

        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            // releases any system resources associated with the stream
            if(iStream!=null)
                iStream.close();
            if(bis!=null)
                bis.close();
        }
    }
}

假设test.txt内容如下:

ABCDE

输出结果为:

Char : A
Char : B
Char : C
Char : D
reset() invoked
char : D
char : E

热门文章

优秀文章