如何使用Java覆盖字节数组中的特定块?
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
热门推荐
10 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特