How to convert a String array to a Byte array? (java)

Code Doggo picture Code Doggo · Feb 3, 2013 · Viewed 53.5k times · Source

I have a one dimensional String array that I want to convert into a one dimensional byte array. How do I do this? Does this require ByteBuffer? How can I do this? (The strings can be any length, just want to know how to go about doing such an act. And after you convert it into a byte array how could I convert it back into a String array?

-Dan

Answer

Sergii Zagriichuk picture Sergii Zagriichuk · Feb 3, 2013

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.