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?
-
I found the following link stackoverflow.com/questions/5368704/… thought it could help.user3245329– user32453292014-07-03 21:23:07 +00:00Commented Jul 3, 2014 at 21:23
-
Do you know how many bytes?Sotirios Delimanolis– Sotirios Delimanolis2014-07-03 21:24:47 +00:00Commented Jul 3, 2014 at 21:24
-
the number of bytes may vary and is unknown at initialisation.luckydonald– luckydonald2014-07-03 22:05:29 +00:00Commented Jul 3, 2014 at 22:05
Add a comment
|
2 Answers
Use ByteArrayOutputStream. This has a toByteArray() method when you are done
http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html
Comments
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)