0

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?

3
  • I found the following link stackoverflow.com/questions/5368704/… thought it could help. Commented Jul 3, 2014 at 21:23
  • Do you know how many bytes? Commented Jul 3, 2014 at 21:24
  • the number of bytes may vary and is unknown at initialisation. Commented Jul 3, 2014 at 22:05

2 Answers 2

5

Use ByteArrayOutputStream. This has a toByteArray() method when you are done

http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.