简体   繁体   English

Java-从1个InputStream读取字节和字符串

[英]Java - Read Bytes and Strings from 1 InputStream

I would like to read String lines and byte arrays from one InputStream. 我想从一个 InputStream读取String行和字节数组。 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. 当我从阅读器中获得一行data16时 ,它意味着:后跟16个字节的字节数组。 And the problem is if I try to read the bytes from stream I get the "data16" ASCII codes. 问题是如果我尝试从流中读取字节,则会得到“ data16” ASCII码。 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. 我知道DataInputStream可以做到:读取字节数组和读取行。 But it's readLine method is deprecated and it can't convert bytes properly to characters. 但是不建议使用readLine方法,并且无法将字节正确转换为字符。

The bytes can also contain 0, 10 and 13 and all other bytes up to 255 字节也可以包含0、10和13,以及所有其他字节,最大为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. BufferedReader不仅读取新行,而且还在缓冲 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. 最好的选择是自己完成整个操作,但是您不必一次读取一个字节,您可以将一个缓冲区读入内存并进行处理以减少实际的I / O。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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