Java 字节数组中的字节数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36583193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Number of bytes in byte array
提问by Yakov
I have an array byte[] arr;
我有一个数组byte[] arr;
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] arr = out.toByteArray();
How can I measure the data size in arr (if it was written to disk or transferred via network)?
Are below approaches are correct - they suppose that sizeof(byte) = 1B
如何测量 arr 中的数据大小(如果它是写入磁盘或通过网络传输的)?以下方法是否正确 - 他们认为sizeof(byte) = 1B
int byteCount = out.size();
int byteMsgCount = arr.length;
采纳答案by christophetd
Yes, by definition the size of a variable of type byteis one byte. So the length of your array is indeed array.lengthbytes.
是的,根据定义,类型变量的大小byte是一个字节。所以你的数组的长度确实是array.length字节。
out.size()will give you the same value, i.e. the number of bytes that you wrote into the output stream.
out.size()将为您提供相同的值,即您写入输出流的字节数。
[Edit] From cricket_007 comment: if you look at the implementation of sizeand toByteArray
[编辑] 来自 cricket_007 评论:如果您查看size和toByteArray
public synchronized byte toByteArray()[] {
return Arrays.copyOf(buf, count);
}
public synchronized int size() {
return count;
}
... so toByteArraybasically copies the current output buffer, up to countbytes. So using sizeis a better solution.
...所以toByteArray基本上复制当前输出缓冲区,最多count字节。所以使用size是一个更好的解决方案。

