How to overwrite a specific chunk in a byte array

不问归期 提交于 2019-12-11 18:14:12

问题


Given a bytearray and a new bytearray of which i need to overwrite its content on the original bytearray but starting from a specific position/offset (A) as shown in the image below(we can say B is the length of the new Array). Also handling the new length if the overwriting exceeds the actual length of the original array.

(this is needed for .WAV file overwriting in different positions).

here is what i have tried so far but no luck.

 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;

}

回答1:


The easiest way is to use a ByteBuffer to wrap your original array:

final ByteBuffer buf = ByteBuffer.wrap(theOriginalArray);
buf.position(whereYouWant);
buf.put(theNewArray);

Note: above code does not check for overflows etc. If an overflow is possible, the code will have to change for something like this and the method should return the array:

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



回答2:


You will probably find Arrays.copyOfRange() to be useful.




回答3:


I have tried to override byteArray as follow..

public static void main(String[] args) {
    byte[] array1 = new byte[10];
    byte[] array2 = new byte[5];
    for (int i = 0; i < array1.length; i++) {
        array1[i] = (byte) 1;
    }
    for (int i = 0; i < array2.length; i++) {
        array2[i] = (byte) 0;
    }
    Test.overrideArray(3, array1, array2);
}

private static void overrideArray(int start, byte[] originalArray, byte[] overrideArray) {
    //add some codes for check validations lengths of Arrays
    for (int i = start; i - start < overrideArray.length; i++) {
        originalArray[i] = overrideArray[i - start];
    }
    for (int i = 0; i < originalArray.length; i++) {
        System.out.println(originalArray[i]);
    }
}


来源:https://stackoverflow.com/questions/21906002/how-to-overwrite-a-specific-chunk-in-a-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!