Reputation: 350
This is my understanding regarding reading a file using BufferedReader
in java. Please correct me if I am wrong somewhere...
Recently I had a requirement where we are required to read a file multiple times.
The usual way which I use is setting a mark()
and doing a reset. But the input parameters to
a mark is an integer and it cannot accept a long number. Is there a way in which we can read the file, a large number of times.
In c++ we can do a seekg on the fstream
and read
the contents once again irrespective of the number of times we want to do so. Is there anything in java which is of this nature.
Upvotes: 2
Views: 4651
Reputation: 311050
Just close the file and read it again.
But review your requirement. Why can't you process it in one pass?
Upvotes: 3
Reputation: 25028
Not much of a good answer but if you want to do random reading and writing then you can use Channels
in java.nio
package.
BufferedReader
is for reading a file when you logically see it as a series of records and records are generally accessed sequentially.
Channel
s allow you to view your file as a series of blocks. Blocks are meant to be read randomly. :)
Using subclass of channel, FileChannel
, you can read what you want from wherever you want. You need to specify two things:
It has a read(dst,pstn)
where dst
is a ByteBuffer
and pstn is a long
position.
Don't worry that it is abstract
because you use it via Files.newByteChannel()
which does all the voodoo needed to make it work :)
Upvotes: 1