Domanda

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).

enter image description here enter image description here

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;

}
È stato utile?

Soluzione

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

Altri suggerimenti

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

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]);
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top