如何使用 Java 覆盖字节数组中的特定块?

java 8object oriented programmingprogramming更新于 2025/4/8 5:07:17

Java 提供了一个 ByteBuffer 类,允许您使用其 wrap() 方法将数组包装到字节缓冲区中。完成后,您可以使用position()方法替换缓冲区的内容:选择起始位置,并使用put()方法替换数据:

示例

import java.nio.ByteBuffer;

public class OverwriteChunkOfByteArray {
   public static void main(String args[]) {
      String str = "Hello how are you what are you doing";
      byte[] byteArray = str.getBytes();
      System.out.println("Contents of the byet array :: ");
     
      for(int i = 0; i<byteArray.length; i++) {
         System.out.println((char)byteArray[i]);
      }
      ByteBuffer buffer = ByteBuffer.wrap(byteArray);
      byte[] newArray = "where do you live ".getBytes();
      buffer.position(18);
      buffer.put(newArray);
      System.out.println("Contents of the byte array after replacement::");
     
      for(int i = 0; i<byteArray.length; i++) {
         System.out.println((char)byteArray[i]);
      }
   }
}

输出

of the byte array ::
H
e
l
l
o

h
o
w

a
r
e

y
o
u

w
h
a
t

a
r
e

y
o
u

d
o
i
n
g
Contents of the byet array after replacement ::
H
e
l
l
o

h
o
w

a
r
e

y
o
u

w
h
e
r
e

d
o

y
o
u

l
i
v
e

相关文章