Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add byte array to another byte array at specific position java

Tags:

java

byte

I want to create a byte array of size 512 bytes.

For the first 100 bytes I want to reserve it for filename, for the next 412 bytes I want to use it to store data from the file itself.

Something like this :

|----100byte for file name ----||------------412 byte for file data------------|

      byte[] buffer = new byte[512];
      add the filename of  byte[] type into the first 100 position
      insert the file data after the first 100 position 

The file name can be less than 100 bytes.

But I am unable to append the file data at the specific position... how should I do that?

like image 766
hao Avatar asked Oct 29 '25 09:10

hao


1 Answers

How about using System.arraycopy()?

byte[] buffer = new byte[data.length + name.length];
System.arraycopy(name, 0, buffer,           0, name.length)
System.arraycopy(data, 0, buffer, name.length, data.length)

You might need to add a check to ensure data.length + name.length does not exceed 512.

To fix the length of the name to 100, do it like this:

byte[] buffer = new byte[100 + name.length];
System.arraycopy(name, 0, buffer,   0, Math.min(100, name.length))
System.arraycopy(data, 0, buffer, 100, data.length)

To fix the total length to 512, add a limit to data.length:

byte[] buffer = new byte[512];
System.arraycopy(name, 0, buffer,   0, Math.min(100, name.length))
System.arraycopy(data, 0, buffer, 100, Math.min(412, data.length))
like image 165
Dorus Avatar answered Oct 31 '25 01:10

Dorus