Convert ArrayList to byte []

后端 未结 3 1772
面向向阳花
面向向阳花 2021-01-04 03:37

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

Can anyone tell me how to convert m

相关标签:
3条回答
  • 2021-01-04 04:04

    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]);
    
    0 讨论(0)
  • 2021-01-04 04:18

    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);
    }
    
    0 讨论(0)
  • 2021-01-04 04:18

    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)

    0 讨论(0)
提交回复
热议问题