1 Reply Latest reply on May 23, 2011 7:31 PM by 796440

    Mixed text/data

      Is there an easy way to read a newline-terminated line of text from an input stream without consuming any of the following bytes (think of a text-based, line-oriented protocol followed by raw data)? The issue is that, according to its API, even InputStreamReader.read() (of a single char) can buffer more data. The following works, but seems to be a lot of work for such a small thing:
      public static String readLine (InputStream in) throws java.io.IOException {
        int l = 0x400;
        int b, i = 0;
        byte[] buf = new byte[l];
        while ((b = in.read()) != -1) {
          if (b == '\n')
            return new String(buf, 0, i, UTF8);
          if (i == l) {
            l *= 2;
            buf = java.util.Arrays.copyOf(buf, l);
          buf[i++] = (byte)b;
        return i == 0 ? null : new String(buf, 0, i, UTF8);
      Am I missing something?

        • 1. Re: Mixed text/data
          It doesn't matter if the InputStream buffers additional data. Once you've read your line of text, you'll be continuing to read from that same InputStream anyway. It doesn't matter if the stream has buffered that data internally or not.

          You might also look into BufferedInputStream's mark() and reset() methods, or PushbackInputStream's unread() methods, if detecting the text/raw border is proving tricky.