如何覆盖字节数组中的特定块

Jal*_*rdo 0 java arrays bytearray overwrite audio-recording

给定一个字节组和一个新的字节组,其中我需要覆盖其上的原始内容bytearray,但开始从特定位置/偏移(A)如下面的图像中(我们可以说B是长度新数组).如果覆盖超过原始数组的实际长度,也处理新长度.

(这是.WAV文件覆盖在不同位置所需的).

在此输入图像描述 在此输入图像描述

这是我到目前为止尝试但没有运气.

 public byte[] ByteArrayAppender(byte[] firstData, byte[] newData, byte[] remainData, int Position) {

    byte[] editedByteArray = new byte[firstData.length + newData.length + remainData.length];


    System.arraycopy(firstData, 0, editedByteArray, 0, Position);

    System.arraycopy(newData, 0, editedByteArray, firstData.length, newData.length);

    System.arraycopy(remainData, 0, editedByteArray, newData.length, remainData.length);

    return editedByteArray;

}
Run Code Online (Sandbox Code Playgroud)

fge*_*fge 8

最简单的方法是使用a ByteBuffer来包装原始数组:

final ByteBuffer buf = ByteBuffer.wrap(theOriginalArray);
buf.position(whereYouWant);
buf.put(theNewArray);
Run Code Online (Sandbox Code Playgroud)

注意:上面的代码不检查溢出等.如果可能发生溢出,代码将不得不改变这样的东西,该方法应该返回数组:

final int targetLength = theNewArray.length + offset;
final boolean overflow = targetLength > theOriginalArray.length;
final ByteBuffer buf;

if (overflow) {
    buf = ByteBuffer.allocate(targetLength);
    buf.put(theOriginalArray);
    buf.rewind();
} else
    buf = ByteBuffer.wrap(theOriginalArray);

buf.position(offset);
buf.put(theNewArray);

return buf.array(); // IMPORTANT
Run Code Online (Sandbox Code Playgroud)