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. So my question is: What is the best and/or efficient way to accomplish that? How to write to that?
Use ByteArrayOutputStream. This has a toByteArray() method when you are done
http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html
I would suggest using of Guava's ByteSource
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).
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.