如何使用 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

更新於:2020-06-16

2000+ 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.