How to overwrite a specific chunk in a byte array using java?


Java provides a ByteBuffer class which allows you to wrap an array into a byte buffer using its wrap() method. Once you did that you can replace the contents of the buffer using the position(): To select the starting position and, put(): To replace the data methods:

Example

Live Demo

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]);
      }
   }
}

Output

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

Updated on: 16-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements