简体   繁体   中英

Java - Read Bytes and Strings from 1 InputStream

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM