Java 将包含 ASCII 字符的字节数组转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18583279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting byte array containing ASCII characters to a String
提问by user1118764
I have a byte array that consists of ASCII characters that I wish to convert to a String. For example:
我有一个字节数组,它由我希望转换为字符串的 ASCII 字符组成。例如:
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 get this string into a String variable?
myByteArray 应该在循环后包含一个字符串“12345678”。如何将此字符串转换为 String 变量?
Thanks!
谢谢!
采纳答案by rocketboy
Use
用
new String(myByteArray, "UTF-8");
String class provides a constructorfor this.
String 类为此提供了一个构造函数。
Side note:The second argument here is the CharSet(byte encoding) which should be handled carefully. More here.