将 2 个字节数组写入 OutputStream 的更好方法是什么?
我有两个字节数组需要写入套接字上的 OutputStream。现在我做了这样的事情:
byte[] arr1, arr2;
OutputStream os;
os.write(arr1);
os.write(arr2);
我想知道是否最好先组合两个数组(例如使用 System.arraycopy() ),然后再调用 os.write(combinedArray )一次?
如果这很重要的话,我是从 Android 的角度来问的。
I have two byte arrays that I need to write to an OutputStream on a Socket. Right now I do something like this:
byte[] arr1, arr2;
OutputStream os;
os.write(arr1);
os.write(arr2);
I was wondering if it's perhaps better to instead first combine the two arrays (e.g. with System.arraycopy()
) and only then call os.write(combinedArray)
once?
And if it matters, I'm asking from an Android perspective.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为从技术上讲,您最好将 OutputStream 包装在 BufferedOutputStream 中,并分别写入每个字节[]。写完后,调用 bufferedOutputStream.flush(); BufferedOutputStream 会在其内部缓冲区满时自动写入,无论您使用单独的字节数组写入多少次,并且调用flush可以确保所有数据都被写入。底层 BufferedOutputStream 将确定何时最有效地为您逻辑组合字节数组,因此您不必用额外的逻辑使代码变得混乱。
I think technically, you'd be better off wrapping your OutputStream in a BufferedOutputStream and write each byte[] separately. When you're done writing, call bufferedOutputStream.flush(); The BufferedOutputStream will automatically write when its own internal buffer gets full, no matter how many times you write to it with separate byte arrays, and the call to flush ensures that all of the data gets written. The underlying BufferedOutputStream will determine when it's most efficient to logically combine the byte arrays for you, so you don't have make your code messy with extra logic.