使用I/o包的BufferedReader 类的mark()方法,遇到了奇怪的情况,就是有时在mark(0)填入0,有些代码能正常表现,有些不能正常。代码如下:
import java.io.*;
class test {
public static void main(String[] args) throws IOException {
try(
BufferedReader r = new BufferedReader(new StringReader(
"Happy Birthday to You!\n" +
"Happy Birthday, dear " + System.getProperty("user.name") + "!"));)
{
if(r.markSupported()) {
r.mark(0); // save the data we are about to read
System.out.println(r.readLine()); // read the first line
r.reset(); // jump back to the marked position
//r.mark(1000); // start saving the data again
System.out.println(r.readLine()); // read the first line again
System.out.println(r.readLine()); // read the second line
r.reset(); // jump back to the marked position
System.out.println(r.readLine()); // read the first line one final
}
}catch (IOException e){
System.out.println(e);
}
}
}
运行出现
Happy Birthday to You!
java.io.IOException: Mark invalid
import java.io.*;
import static java.lang.System.out;
public class App {
public static final String TEST_STR = "Line 111111111111111111\nLine 222222222222222222\nLine 33333333333333333333333\nLine 4444444444444444444444\n";
public static void main(String[] args) {
try (BufferedReader in = new BufferedReader(new StringReader(TEST_STR))) {
// first check if this Reader support mark operation
if (in.markSupported()) {
out.println(in.readLine());
in.mark(0); // mark 'Line 2'
out.println(in.readLine());
out.println(in.readLine());
in.reset(); // reset 'Line 2'
out.println(in.readLine());
in.reset(); // reset 'Line 2'
out.println(in.readLine());
in.mark(0); // mark 'Line 3'
out.println(in.readLine());
in.reset(); // reset 'Line 3'
out.println(in.readLine());
out.println(in.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行没有问题。
Line 111111111111111111
Line 222222222222222222
Line 33333333333333333333333
Line 222222222222222222
Line 222222222222222222
Line 33333333333333333333333
Line 33333333333333333333333
Line 4444444444444444444444
运行在intellij idea上。
请各位大侠指出那个地方出问题了。