Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ArrayList<String> to byte []

Tags:

java

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!

like image 262
jboy Avatar asked Apr 11 '11 08:04

jboy


People also ask

How to convert String to byte[] Java?

How to convert String to byte[] in Java? In Java, we can use str. getBytes(StandardCharsets. UTF_8) to convert a String into a byte[] .

How to convert ArrayList to byte array in Java?

I have added sample coding for convert ArrayList to byte[]. 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.


1 Answers

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);
}
like image 116
WhiteFang34 Avatar answered Sep 21 '22 01:09

WhiteFang34