Home > DeveloperSection > Forums > How can I Read lines from Java FileInputStream without misplacing my place
Aaron Douglas
Aaron Douglas

Total Post:20

Posted on    September-28-2013 8:00 AM

 Java Java 

 1 Reply(s)
 1072  View(s)
Rate this:
I have a FileInputStream. I would like to read character-oriented, line wise data from it, until I find a particular delimiter. Then I'd like to pass the FileInputStream, with the current position set immediately after the end of the delimiter line, to a library that needs an InputStream.

I can use a BufferedReader to walk through the file a line at a time, and everything works great. However, this leaves the underlying file stream in

BufferedReader br = new BufferedReader(new InputStreamReader(myFileStream))

at a non-deterministic position -- the BufferedReader had to look ahead, and I don't know how far, and AFAICT there's no way to tell the BufferedReader to rewind the underlying stream to just after the last-returned line.

Is this the best solution? It seems crazy to have aReaderInputStream(BufferedReader(InputStreamReader(FileInputStream))) but it's the only way I've seen to avoid rolling my own. I'd really like to avoid writing my own entire stream-that-reads-lines implementation if at all possible.

Madam Walker
Madam Walker

Total Post:22

Posted on    September-28-2013 8:57 AM

Hey Aaron!

You can’t unbuffer a buffered reader. You have to use the same wrapper for the life for the application. In your situation I would use

DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
String line = dis.readLine();

While DataInputStream.readLine() is deprecated, it could work for you if you are careful. Otherwise you only option is to read the bytes yourself and parse the text using the encoding required.

Don't want to miss updates? Please click the below button!

Follow MindStick