Java.io.Reader.mark() 方法



描述

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

声明

以下是 java.io.Reader.mark() 方法的声明。

public void mark(int readAheadLimit)

参数

readAheadLimit − 在仍然保留标记的情况下可以读取的字符数的限制。读取这么多字符后,尝试重置流可能会失败。

返回值

此方法不返回值。

异常

IOException − 如果流不支持 mark(),或者发生其他 I/O 错误

示例

以下示例显示了 java.io.Reader.mark() 方法的使用。

package com.tutorialspoint;

import java.io.*;

public class ReaderDemo {
   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
java_io_reader.htm
广告

© . All rights reserved.