转换ArrayList< String>到byte [] [英] Convert ArrayList<String> to byte []
问题描述
我有一个 ArrayList< String>
我想通过UDP发送但send方法需要 byte []
。
I have an ArrayList<String>
that i want to send through UDP but the send method requires byte[]
.
任何人都可以告诉我如何将 ArrayList< String>
转换为 byte []
?
Can anyone tell me how to convert my ArrayList<String>
to byte[]
?
谢谢!
推荐答案
这取决于你的期望在另一端解码这些字节。一种合理的方法是对列表中的每个字符串使用像 DataOutputStream
这样的UTF-8编码。对于字符串,它为UTF-8编码的长度写入2个字节,后跟UTF-8字节。如果您不在另一端使用Java,这将是可移植的。以下是使用Java为双方编码和解码 ArrayList< String>
的示例:
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);
}
这篇关于转换ArrayList< String>到byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!