"how to convert a string array to a byte array? (java)" Code Answer

5

array to array you should convert manually with parsing into both sides, but if you have just a string you can string.getbytes() and new string(byte[] data); like this

public static void main(string[] args) {
    string[] strings = new string[]{"first", "second"};
    system.out.println(arrays.tostring(strings));
    byte[][] bytestrings = converttobytes(strings);
    strings = converttostrings(bytestrings);
    system.out.println(arrays.tostring(strings));

}

private static string[] converttostrings(byte[][] bytestrings) {
    string[] data = new string[bytestrings.length];
    for (int i = 0; i < bytestrings.length; i++) {
        data[i] = new string(bytestrings[i], charset.defaultcharset());

    }
    return data;
}


private static byte[][] converttobytes(string[] strings) {
    byte[][] data = new byte[strings.length][];
    for (int i = 0; i < strings.length; i++) {
        string string = strings[i];
        data[i] = string.getbytes(charset.defaultcharset()); // you can chose charset
    }
    return data;
}

for one byte[] from string[] you have to:

  • to bytearray concat byte arrays from each string using some delimeter
  • from bytearray split by te same delimiter and create string as i described above.
By Fai Ng on May 25 2022

Answers related to “how to convert a string array to a byte array? (java)”

Only authorized users can answer the Search term. Please sign in first, or register a free account.