Java Reader mark()方法

java.io.Reader.mark(int readAheadLimit) 标记了流中的当前位置。后续调用reset()将尝试将该流重新定位到这一点。

1 语法

public void mark(int readAheadLimit)

2 参数

readAheadLimit:在仍保留该标记的情况下被读取的字符数限制。读取这些字符后,尝试重置流可能会失败。

3 返回值

4 示例 

package com.yiidian;

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

public class Demo {
    public static void main(String[] args) {

        try {
            String s = "Hello World";

            // create a new StringReader
            Reader reader = new StringReader(s);

            // read the first five chars
            for (int i = 0; i < 5; i++) {
                char c = (char) reader.read();
                System.out.print("" + c);
            }

            // mark current position for maximum of 10 characters
            reader.mark(10);

            // read five more chars
            for (int i = 0; i < 6; i++) {
                char c = (char) reader.read();
                System.out.print("" + c);
            }

            // reset back to the marked position
            reader.reset();

            // change line
            System.out.println();

            // read six more chars
            for (int i = 0; i < 6; i++) {
                char c = (char) reader.read();
                System.out.print("" + c);
            }

            // close the stream
            reader.close();

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

输出结果为:

Hello World
 World

热门文章

优秀文章