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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:14:32  来源:igfitidea点击:

Converting byte array containing ASCII characters to a String

javastringbytearray

提问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.

旁注:这里的第二个参数是应该小心处理的CharSet(字节编码)。更多在这里。

回答by Java Devil

String aString = new String(yourByteArray);

or

或者

String aString = new String(yourByteArray, "aCharSet"); 
//Replacing "aCharSet" with the appropriate chararacter set

Easy See docs

轻松查看文档