简体   繁体   English

转换ArrayList <String> 到byte []

[英]Convert ArrayList<String> to byte []

I have an ArrayList<String> that i want to send through UDP but the send method requires byte[] . 我有一个我想通过UDP发送的ArrayList<String> ,但send方法需要byte[]

Can anyone tell me how to convert my ArrayList<String> to byte[] ? 谁能告诉我如何将我的ArrayList<String>转换为byte[]

Thank you! 谢谢!

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. 一种合理的方法是使用像DataOutputStream这样的UTF-8编码为列表中的每个字符串。 For a string it writes 2 bytes for the length of the UTF-8 encoding followed by the UTF-8 bytes. 对于字符串,它为UTF-8编码的长度写入2个字节,后跟UTF-8字节。 This would be portable if you're not using Java on the other end. 如果您不在另一端使用Java,这将是可移植的。 Here's an example of encoding and decoding an ArrayList<String> in this way using Java for both sides: 以下是使用Java为这两方ArrayList<String>和解码ArrayList<String>的示例:

// 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);
}

If the other side is also java, you can use ObjectOutputStream . 如果另一方也是java,则可以使用ObjectOutputStream It will serialize the object (you can use a ByteArrayOutputStream to get the bytes written) 它将序列化对象(您可以使用ByteArrayOutputStream来获取写入的字节)

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. 替代解决方案是将ArrayList中的每个字符串中的每个字节添加到List中,然后将该列表转换为数组。

    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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM