Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

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

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 byte? Is it as simple as calling

String str = new String( arr );

Will the String constructor know to automatically stop at the null terminating character? Any bytes after the null byte are (possibly) garbage characters that I don't want to include in the string. The last response under Parsing byte array containg fields of unknown length suggests looping through the array and manually finding the null terminating character, but I was wondering whether the String constructor will do this automatically. I also assume the system's default charset will be used on all ends.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
byte arr[] = ...
Charset charset = ...

// Find the position of the first zero byte
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...