如何覆盖字节数组中的特定块 [英] How to overwrite a specific chunk in a byte array

查看:82
本文介绍了如何覆盖字节数组中的特定块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

(这是在不同位置覆盖 .WAV 文件的必要条件.)

(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;

}

推荐答案

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

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

这篇关于如何覆盖字节数组中的特定块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆