15

I have an ArrayList<String> that i want to send through UDP but the send method requires byte[].

Can anyone tell me how to convert my ArrayList<String> to byte[]?

Thank you!

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
jboy
  • 161
  • 1
  • 1
  • 4

3 Answers3

21

It really depends on how you expect to decode these bytes on the other end. One reasonable way would be to use UTF-8 encoding like DataOutputStream does for each string in the list. For a string it writes 2 bytes for the length of the UTF-8 encoding followed by the UTF-8 bytes. This would be portable if you're not using Java on the other end. Here's an example of encoding and decoding an ArrayList<String> in this way using Java for both sides:

// example input list
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
list.add("baz");

// write to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
for (String element : list) {
    out.writeUTF(element);
}
byte[] bytes = baos.toByteArray();

// read from byte array
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(bais);
while (in.available() > 0) {
    String element = in.readUTF();
    System.out.println(element);
}
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
11

If the other side is also java, you can use ObjectOutputStream. It will serialize the object (you can use a ByteArrayOutputStream to get the bytes written)

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

Alternative solution would be simply to add every byte in every string in the ArrayList to a List and then convert that list to an array.

    List<String> list = new ArrayList<>();
    list.add("word1");
    list.add("word2");

    int numBytes = 0;
    for (String str: list)
        numBytes += str.getBytes().length;

    List<Byte> byteList = new ArrayList<>();

    for (String str: list) {
        byte[] currentByteArr = str.getBytes();
        for (byte b: currentByteArr)
            byteList.add(b);
    }
    Byte[] byteArr = byteList.toArray(new Byte[numBytes]);
faris
  • 692
  • 4
  • 18