How to convert Strings to and from UTF8 byte arrays in Java

前端 未结 13 2369
终归单人心
终归单人心 2020-11-22 13:05

In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to c

13条回答
  •  旧巷少年郎
    2020-11-22 13:24

    For decoding a series of bytes to a normal string message I finally got it working with UTF-8 encoding with this code:

    /* Convert a list of UTF-8 numbers to a normal String
     * Usefull for decoding a jms message that is delivered as a sequence of bytes instead of plain text
     */
    public String convertUtf8NumbersToString(String[] numbers){
        int length = numbers.length;
        byte[] data = new byte[length];
    
        for(int i = 0; i< length; i++){
            data[i] = Byte.parseByte(numbers[i]);
        }
        return new String(data, Charset.forName("UTF-8"));
    }
    

提交回复
热议问题