java reader mark_Java Reader mark()方法

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,`Reader`是一个抽象类,用于读取字符流。`Reader`类提供了`reset()`方法,可以重置字符流的读取位置。 `reset()`方法的作用是将读取位置恢复到最后一次调用`mark()`方法时的位置。如果没有调用过`mark()`方法,那么调用`reset()`方法将抛出`IOException`异常。 以下是`Reader`类中`reset()`方法的声明: ```java public void reset() throws IOException ``` 使用`reset()`方法时需要注意以下几点: 1. 调用`reset()`方法之前必须调用`mark()`方法,否则会抛出`IOException`异常。 2. 如果上一次调用`mark()`方法时已经读取了比`mark`参数更多的字符,则`reset()`方法可能会失败。 3. `reset()`方法可能会失败,因为在某些情况下,无法在缓冲区内保存足够的字符来满足`reset()`方法的需求。 4. `reset()`方法可能会抛出`IOException`异常,因为某些字符流不支持`mark()`和`reset()`方法。 下面是一个简单的示例代码,演示如何使用`reset()`方法: ```java import java.io.*; public class ReaderDemo { public static void main(String[] args) throws Exception { Reader reader = new FileReader("test.txt"); if (reader.markSupported()) { reader.mark(0); char[] buf = new char[1024]; int len = reader.read(buf); System.out.println(new String(buf, 0, len)); reader.reset(); len = reader.read(buf); System.out.println(new String(buf, 0, len)); } else { System.out.println("mark/reset not supported"); } reader.close(); } } ``` 在上面的代码中,首先使用`FileReader`类创建了一个`Reader`对象,并调用`markSupported()`方法检查该字符流是否支持`mark()`和`reset()`方法。如果支持,就调用`mark()`方法来标记读取位置,然后读取一部分字符并输出。接着调用`reset()`方法来将读取位置恢复到标记的位置,再次读取并输出字符。最后关闭`Reader`对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值