Re: convenient way to read text file multiple times without reopening it



Tomas Mikula wrote:

Hi,

I suppose that a convenient way to read text file is through FileReader.
But FileReader does not support the reset().

Could you create a FileInputStream, and then create your FileReader from the
FileReader(FileDescriptor) constructor, using FileInputStream.getFD() to get
the FileDescriptor?

FileInputStream also doesn't support reset() (does any file class actually
support a reset() method?), but you can "coerce" it by using NIO, namely
FileInputStream.getChannel().position(0);

Not neat, but at least it keeps the file open.


So, as a temporal remedy, I am opening the file twice:

Reader fr = new FileReader("filename");
.....
fr.close();
.....
fr = new FileReader("filename");
.....


Of course this is not a clean way. At least, the file could possibly be
removed or renamed by another program between the two calls to "new
FileReader()".

Indeed. If that is a possibility then you need to keep the file open.

So I want to open the file once and then read it
(sequentially) twice.
I suppose Java provides a convenient way for doing it, but I'm unable to
figure it out.

I couldn't figure out a convenient way.


Thank you for pointing me the right way!

I wouldn't call this "the right way", more a case of "a way that works".

--
Nigel Wade, System Administrator, Space Plasma Physics Group,
University of Leicester, Leicester, LE1 7RH, UK
E-mail : nmw@xxxxxxxxxxxx
Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555
.



Relevant Pages