Easy way to concatenate two byte arrays

前端 未结 12 1528
一个人的身影
一个人的身影 2020-12-02 04:25

What is the easy way to concatenate two byte arrays?

Say,

byte a[];
byte b[];

How do I concatenate two byte

相关标签:
12条回答
  • 2020-12-02 05:19

    You can use third party libraries for Clean Code like Apache Commons Lang and use it like:

    byte[] bytes = ArrayUtils.addAll(a, b);
    
    0 讨论(0)
  • 2020-12-02 05:20

    Here's a nice solution using Guava's com.google.common.primitives.Bytes:

    byte[] c = Bytes.concat(a, b);
    

    The great thing about this method is that it has a varargs signature:

    public static byte[] concat(byte[]... arrays)
    

    which means that you can concatenate an arbitrary number of arrays in a single method call.

    0 讨论(0)
  • 2020-12-02 05:20
    byte[] result = new byte[a.length + b.length];
    // copy a to result
    System.arraycopy(a, 0, result, 0, a.length);
    // copy b to result
    System.arraycopy(b, 0, result, a.length, b.length);
    
    0 讨论(0)
  • 2020-12-02 05:21

    Most straightforward:

    byte[] c = new byte[a.length + b.length];
    System.arraycopy(a, 0, c, 0, a.length);
    System.arraycopy(b, 0, c, a.length, b.length);
    
    0 讨论(0)
  • 2020-12-02 05:24

    The most elegant way to do this is with a ByteArrayOutputStream.

    byte a[];
    byte b[];
    
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
    outputStream.write( a );
    outputStream.write( b );
    
    byte c[] = outputStream.toByteArray( );
    
    0 讨论(0)
  • 2020-12-02 05:24

    If you prefer ByteBuffer like @kalefranz, there is always the posibility to concatenate two byte[] (or even more) in one line, like this:

    byte[] c = ByteBuffer.allocate(a.length+b.length).put(a).put(b).array();
    
    0 讨论(0)
提交回复
热议问题