开发者

Java make a copy of a reader

I have a BufferedReader looping through a file. When I hit a specific case, I would like to continue looping using a different instance of the reader but starti开发者_StackOverflow社区ng at this point.

Any ideas for a recommended solution? Create a separate reader, use the mark function, etc.?


While waiting for your answer to my comment, I'm stuck with making assumptions.

If it's the linewise input you value, you may be as pleasantly surprised as I was to discover that RandomAccessFile now (since 1.4 or 1.5) supports the readLine method. Of course RandomAccessFile gives you fine-grained control over position.

If you want buffered IO, you may consider wrapping a reader around a CharacterBuffer or maybe a ByteBuffer wrapped around a file mapped using the nio API. This gives you the ability to treat a file as memory, with fine control of the read pointer. And because the data is all in memory, buffering is included free of charge.


Have you looked at BufferedReader's mark method? Used in conjunction with reset it might meet your needs.


If you keep track of how many characters you've read so far, you can create a new BufferedReader and use skip.

As Noel has pointed out, you would need to avoid using BufferedReader.readLine(), since readLine() will discard newlines and make your character count inaccurate. You probably shouldn't count on readLine() never getting called if anyone else will ever have to maintain your code.

If you do decide to use skip, you should write your own buffered Reader which will give you an offset counting the newlines.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜