C
C
Chvalov2015-10-29 12:54:24
Java
Chvalov, 2015-10-29 12:54:24

How to concatenate an array to an array (byte) in Java?

There is an array of byte type, byte_1 and byte_2
How can I combine them into one whole so that at the output I get
mass = byte_1 + byte_2; ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Kornachev, 2015-10-29
@Chvalov

Using the standard library

ByteArrayOutputStream outStream = new ByteArrayOutputStream();
outStream.write(byte_1);
outStream.write(byte_2);
byte[] mass = outStream.toByteArray();

And the second option
byte[] mass = new byte[byte_1.length() + byte_2.length()]
System.arrayCopy(byte_1, 0, mass, 0, byte_1.length());
System.arrayCopy(byte_2, 0, mass, byte_1.length(), byte_2.length());

E
Evhen, 2015-10-29
@EugeneP2

In any case, you need to create a new array with a length of byte_1.length + byte_2.length
Again, I recommend using ready-made solutions

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.4</version>
</dependency>

Class: org.apache.commons.lang3.ArrayUtils
Method: ArrayUtils.addAll(arr1, arr2)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question