Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a line from InputStream without buffering the input? [duplicate]

I have an InputStream which contains a line as a string and then binary data.

If I read the line using new BufferedReader(new InputStreamReader(inputStream)), the binary data is being also read and cannot be re-read.

How can I read a line without reading the binary data as well?

like image 900
AlikElzin-kilaka Avatar asked Nov 11 '22 03:11

AlikElzin-kilaka


1 Answers

Eventually did it manually directly reading byte after byte from the InputStream without wrapping the InputStream. Everything I tried, like Scanner and InputStreamReader, reads ahead (buffers) the input :(

I guess I missed a some cases like \r.

public static String readLine(InputStream inputStream) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int c;
    for (c = inputStream.read(); c != '\n' && c != -1 ; c = inputStream.read()) {
        byteArrayOutputStream.write(c);
    }
    if (c == -1 && byteArrayOutputStream.size() == 0) {
        return null;
    }
    String line = byteArrayOutputStream.toString("UTF-8");
    return line;
}
like image 150
AlikElzin-kilaka Avatar answered Nov 14 '22 23:11

AlikElzin-kilaka