How do I convert a byte array with null terminating character to a String in Java?

前端 未结 4 1434
忘掉有多难
忘掉有多难 2020-12-03 13:38

How can I create a String object from a byte array

byte arr[MAX_SIZE];  // Java

where one of the array elements is a C null terminating byt

4条回答
  •  被撕碎了的回忆
    2020-12-03 14:09

    byte arr[] = ...
    Charset charset = ...
    int i;
    for (i = 0; i < arr.length && arr[i] != 0; i++) { }
    String str = new String(arr, 0, i, charSet);
    

    Notes:

    • It is generally a good idea to use an explicit CharSet parameter so that your application doesn't depend on the platform's default characterset / encoding.

    • This won't work for some charsets. For instance, a UTF-16 encoded string can't safely be represented as a zero-terminated byte sequence because many code units contain zero bytes. (On the other hand, UTF-8 is OK provided that the string contains no instances of code point zero; see Can UTF-8 contain zero byte?)

    ... but I was wondering whether the String constructor will do this automatically.

    No it / they won't. (Don't "wonder" ... read the javadoc :-))

    I also assume the system's default charset will be used on all ends.

    If you don't specify a charset, the Java platform's default will be used. This is likely to be the system default, but that is not guaranteed.

提交回复
热议问题