Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

java - What are mark and reset in BufferedReader?

I would like to know what are the mark() and reset() methods of BufferedReader? How do I use them? I read the Javadoc but as a beginner I was unable to understand it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The mark and reset methods of streams provide a way to jump backwards in the stream and re-read data.

When you call mark() on a BufferedReader it will begin keeping data you read from that point forwards in its internal buffer. When you call reset() it will jump back to the marked position of the stream, so the next read()s will be satisfied by the in-memory buffer. When you read past the end of that buffer, then it will seamlessly go back to reading fresh data. BufferedInputStream works the same way.

The int parameter to mark tells it the maximum number of characters (for BufferedReader) or bytes (for BufferedInputStream) that you want to be able to go backwards. If you read too much data past the marked position, then the mark can be "invalidated", and calling reset() will fail with an exception.

A little example:

BufferedReader r = new BufferedReader(new StringReader(
    "Happy Birthday to You!
" +
    "Happy Birthday, dear " + System.getProperty("user.name") + "!"));
r.mark(1000); // 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 time

In that example, I wrapped the StringReader in a BufferedReader to get the readLine() method, but StringReaders already support mark and reset on their own! Streams that read from an in-memory data source usually support mark and reset themselves, because they already have all the data in memory so it is easy for them to read it again. Streams that read from files or pipes or network sockets do not naturally support mark and reset, but you can always add that feature to any stream by wrapping it in a BufferedInputStream or BufferedReader.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...