javaarraysbyterecordsector

Inserting String into byte array at certain index in Java


I would like to insert a string value into a specific range of indexes in an already declared byte array. How would I do this?

byte [] sector = new byte[SECTORSIZE];
String str1 = "Sector 0, Record 0";
//I want to insert str1 into sector at indexes 0 - str1.length()
String str2 = "Sector 0, Record 1";
//I want to insert str2 into sector at indexes 128 - str2.length() + 128

Solution

  • After you get the arrays of bytes for your strings you can use

       System.arraycopy(src, srcPos, dest, destPos, length);
    

    see java docs for this method for more info