Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read the first line in a stream and remove it from the stream

Tags:

java

I have 2 classes who must read an InputStream, the first one should only interpret the first line of the stream BUT the first line should be removed from the stream so that class B can interpret everything after the first line. Which doesn't work when I pass my InputStream to a BufferedReader and do a readLine().

I know I could do a read on the stream until I've encountered a \b but maybe a more proper solution exists to do the job?

// Reads the first line from the stream and everything else
public String retrieveFileNameFromTheFirstLineInInputStream(InputStream in) throws IOException {
    InputStreamReader isReader = new InputStreamReader(in);
    BufferedReader reader = new BufferedReader(isReader);
    return reader.readLine();
}
like image 832
Stijn Vanpoucke Avatar asked Feb 27 '23 14:02

Stijn Vanpoucke


1 Answers

You can't remove something from an InputStream, you just can read from it. Don't use the BufferedReader to read the line, because it surely will read much more than the first line from the InputStreamReader (to fill its buffer) which itself reads from the InputStream.

I'd suggest to read using the InputStreamReader until the end of the line is reached, then pass the InputStream instance to your code which should read it.

BTW, you always should specify the encoding used by the InputStreamReader, otherwise the system encoding will be used to convert the bytes from the InputStream to characters which can differ on different machines.

like image 57
Mot Avatar answered Apr 02 '23 09:04

Mot