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?
Asked
Active
Viewed 2,564 times
0

luckydonald
- 5,976
- 4
- 38
- 58
-
I found the following link http://stackoverflow.com/questions/5368704/appending-a-byte-to-the-end-of-another-byte thought it could help. – user3245329 Jul 03 '14 at 21:23
-
Do you know how many bytes? – Sotirios Delimanolis Jul 03 '14 at 21:24
-
the number of bytes may vary and is unknown at initialisation. – luckydonald Jul 03 '14 at 22:05
2 Answers
5
Use ByteArrayOutputStream. This has a toByteArray() method when you are done
http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html

Strikeskids
- 3,932
- 13
- 27
0
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)

30thh
- 10,861
- 6
- 32
- 42