简体   繁体   English

从InputStream读取字节块

[英]Reading chunks of bytes from an InputStream

In my application I'am receiving a byte stream via Bluetooth. 在我的应用程序中,我正在通过蓝牙接收字节流。 I am using DataInputStream to read a fixed amount of bytes at once from an input stream: 我正在使用DataInputStream一次从输入流中读取固定数量的字节:

private final InputStream mInStream = ...
...
DataInputStream dataInputStream = new DataInputStream(mInStream);
...
while(true) {
... = dataInputStream.readFully(buffer,0,length);
}

Can i improve performance by wrapping mInStream in a BufferedInputStream and put this BufferedInputStream into DataInputStream ? 我可以通过将mInStream包装在BufferedInputStream并将此BufferedInputStream放入DataInputStream提高性能吗? Eg: 例如:

private final InputStream mInStream = ...
...
BufferedInputStream buffInStream = new BufferedInputStream(mInStream);
DataInputStream dataInputStream = new DataInputStream(buffInStream);
...
while(true) {
... = dataInputStream.readFully(buffer,0,length);
}

Will this gain performance? 这样会提高性能吗? Or will it stay the same since i am reading a constant number of bytes from the inputstream? 还是因为我从输入流中读取了恒定数量的字节,它会保持不变吗?

thanks 谢谢

Can i improve performance by wrapping mInStream in a BufferedInputStream and put this BufferedInputStream into DataInputStream? 我可以通过将mInStream包装在BufferedInputStream中并将此BufferedInputStream放入DataInputStream中来提高性能吗?

It depends on how large the buffer you're reading into is. 这取决于您要读入的缓冲区有多大。 The default internal buffer of a BufferedInputStream is 8k bytes. BufferedInputStream的默认内部缓冲区为8k字节。 If your own buffer is comparable to or larger than this, there is no advantage. 如果您自己的缓冲区等于或大于此缓冲区,则没有任何优势。 If your buffer is say 128 or 256 bytes there almost certainly is. 如果缓冲区是128或256字节,几乎可以肯定是。

... = dataInputStream.readFully(buffer,0,length);

readFully() doesn't return a value. readFully()不返回值。 You should only use this method when you're sure that you want exactly this many bytes, and that they should all be present in the input. 仅在确定确实需要这么多字节并且输入中都应包含所有字节时,才应使用此方法。 If the remaining input is shorter than 'length it will throw EOFException and you will lose any data that has been partially read. 如果其余输入的长度小于'length则它将抛出EOFException并且您将丢失所有已部分读取的数据。 If you're not sure how much data should be read you should use read(byte[]) or read(byte[], int, int). 如果不确定要读取多少数据,则应使用read(byte[])read(byte[], int, int).

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

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