7

Does Java have a simple method to read a line from an InputStream without buffering? BufferedReader is not suitable for my needs because I need to transfer both text and binary data through the same connection repeatedly and buffering just gets in the way.

3
  • Through binary data, you don't have lines, right? How about recognizing if your data is text or binary?
    – belgther
    Dec 13, 2011 at 11:32
  • 1
    I do have them. The request starts with text lines describing it and sometimes is followed by binary data.
    – Ree
    Dec 13, 2011 at 11:35
  • Possible duplicate: stackoverflow.com/questions/25215564/… Aug 15, 2014 at 19:55

3 Answers 3

7

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;
}
0

You could try the Scanner class: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

However, this may buffer the input if no newline characters are present:

Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

2
  • Scanner buffers the input even past the newline :( Aug 15, 2014 at 19:54
  • Scanner does buffers past the newline. I have a StringReader with seven lines and Scanner buffers them all in one shot. May 5, 2016 at 6:06
-3

You may be better off reading the InputStream with a BufferedReader and appending the read lines to a String.

You can then manipulate the String as you wish without worrying about buffering.

2
  • 2
    The problem is that I have no control how BufferedReader reads input. It may read a line and a chunk of data PAST it. I don't want that.
    – Ree
    Dec 13, 2011 at 11:53
  • @Ree, I think that Scanner only buffers backwards, not forward.
    – Tudor
    Dec 13, 2011 at 12:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.