views:

102

answers:

3

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 starting at this point.

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

A: 

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

Alex B
mark is tough to use because i don't know the size of the incoming buffer (or how far through the buffer i am)
yankee2905
Why are you using BufferedReader? Is it for performance or to use the readLine() method?
Carl Smotricz
(as opposed to a plain FileReader, I mean)
Carl Smotricz
yes, it is for performance reasons.
yankee2905
+1  A: 

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.

Carl Smotricz
Yes, that was it, the `RandomAccessFile` :)
BalusC
A: 

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.

rob
Workable if use of BufferedReader.readLine() is avoided, which discards newline data, or newline utilization is standardized.
Noel Ang