[英]Java: Appendable byte array
I want to append bytes to an byte array. 我想将字节追加到字节数组。 The result should be type
byte[]
, with adding single byte
's after calculating them, to it. 结果应为
byte[]
类型,并在计算完后将其添加为单个byte
。 So my question is: What is the best and/or efficient way to accomplish that? 所以我的问题是:什么是最好的和/或最有效的方法? How to write to that?
怎么写呢?
Use ByteArrayOutputStream. 使用ByteArrayOutputStream。 This has a toByteArray() method when you are done
完成后,它具有toByteArray()方法
http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html
I would suggest using of Guava's ByteSource 我建议使用番石榴的ByteSource
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html
It is much more efficient because of using a chains of small chunks inside instead of reallocating memory for a huge array (as ByteArrayOutputStream does). 由于使用了内部的小块链而不是为大型数组重新分配内存(如ByteArrayOutputStream那样),因此效率更高。
Here is an example: 这是一个例子:
byte[] buffer = new byte[1024];
List<ByteSource> loaded = new ArrayList<ByteSource>();
while (true) {
int read = input.read(buffer);
if (read == -1) break;
loaded.add(ByteSource.wrap(Arrays.copyOf(buffer, read)));
}
ByteSource result = ByteSource.concat(loaded)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.