Reputation: 6856
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?
Upvotes: 0
Views: 2833
Reputation: 11376
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)
Upvotes: 0
Reputation: 4052
Use ByteArrayOutputStream. This has a toByteArray() method when you are done
http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html
Upvotes: 5