1

I would like to read String lines and byte arrays from one InputStream. I'm doing it like that at the time:

// stream for reading byte arrays
InputStream stream = process.getInputStream();
// reader for reading String lines
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

String msg = reader.readLine();
// if (msg == "data16")
byte[] bytes = new byte[16];
stream.read(bytes);

When I get a line data16 from reader it means: byte array of 16 bytes follow. And the problem is if I try to read the bytes from stream I get the "data16" ASCII codes. So that means the stream doesn't update the position when I read with reader. Is there a way to synchronize their positions ? I know DataInputStream can do both: read byte arrays and read lines. But it's readLine method is deprecated and it can't convert bytes properly to characters.

The bytes can also contain 0, 10 and 13 and all other bytes up to 255

Performance is important so I don't really want to read byte-after-byte or char-after-char. Also if possible I would like to avoid to "manually" count the bytes and chars read to use the "skip" methods then.

1
  • This is a weird idea to mix binary and text data. I think the right approach in your case (read some metadata e.g. "byte array of 16 bytes follow") is: *byte-after-byte reading; *parse command (data16); *parse following data; Commented Jan 11, 2013 at 11:10

1 Answer 1

1

I don't think you're going to be able to do what you want. The BufferedReader isn't just reading up to the new line, it's buffering the data from the InputStream.

Your best bet will be to just do the whole thing yourself but you don't have to read a byte at a time, you can read a buffer into memory and work on that to cut down on your actual I/O.

Sign up to request clarification or add additional context in comments.

2 Comments

You think the buffering of BufferedReader is the problem ? Then I'll try to read everything with the InputStream and combine some bytes to Strings then.
If you look at the source for BufferedInputStream you can see exactly what it does for the processing of newline characters. You're going to end up doing something very similar yourself

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.