Convert ArrayList <String> to Byte []

I have an ArrayList<String> that I want to send via UDP, but byte[] is required for the send method.

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

Thanks!

+13
source share
2 answers

It really depends on how you plan to decode these bytes on the other end. One reasonable way would be to use UTF-8 encoding such as DataOutputStream for each row in the list. For a string, it writes 2 bytes for the length of the UTF-8 encoding, followed by UTF-8 bytes. This would be portable if you are not using Java on the other end. Here's an example of encoding and decoding an ArrayList<String> 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); } 
+15
source

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

+9
source

Source: https://habr.com/ru/post/1386564/


All Articles