Java: Interleave Bytes and Characters

I have a piece of test equipment, from which I can read data using an InputStream
, which intersperses bytes and characters (organized into lines), e.g.:

{500 binary bytes follows here}
{600 binary bytes follows here}

I’d like to use BufferedReader so I can read a line at a time, but then switch to InputStream so I can read the binary bytes. But this neither seems to work nor seems like a good idea.

How can I do this? I can’t get bytes from a BufferedReader, and if I use a BufferedReader on top of an InputStream, it seems like the BufferedReader “owns” the InputStream.

Edit: the alternative, just using an InputStream everywhere and having to convert bytes->characters and look for newlines, seems like it would definitely work but would also be a real pain.

When using BufferedReader
, you can just use String#getBytes()
to get the bytes out of a String
line. Don’t forget to take character encoding into account. I recommend using UTF-8
all the time.

Just for your information: from the other side, if you only have bytes and you want to construct the characters, just use new String(bytes)
. Also don’t forget to take the character encoding into account here.

[Edit] after all, it’s a better idea to use BufferedInputStream and construct a byte buffer for a single line (fill until the byte matches the linebreak) and test if the character representation of its start matches with one of the predefined strings.

Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Java: Interleave Bytes and Characters

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录