Java – converts a byte array containing ASCII characters to a string

I have a byte array consisting of ASCII characters that I want to convert to a string For example:

byte[] myByteArray = new byte[8];
for (int i=0; i<8; i++) {
    byte[i] = (byte) ('0' + i);
}

Mybytearray should contain a string "12345678" after the loop How do I convert this string to a string variable?

thank you!

Solution

use

new String(myByteArray,"UTF-8");

The string class provides a constructor

Side note: the second parameter is charset, which should be handled carefully More here.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>