如何在 Java (Android) 中将字节数组转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12781872/
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
How to convert byte array to string in Java (Android)
提问by kbalar
I am converting byte array to String by:
我通过以下方式将字节数组转换为字符串:
public static String byteArrayToString(byte[] bytes)
{
return new String(bytes);
}
But this approach is taking much time. Is there any efficient way to convert byte array to String?
但是这种方法需要很长时间。有没有什么有效的方法可以将字节数组转换为字符串?
回答by LordOfThePigs
There is no better way that I know of. And you should always use the constructor that takes the encoding with it, or its pretty much guaranteed that you'll end up with screwed up characters if you deal with any language other than english. ie: you really should be using new String(bytes, "UTF-8")
(obviously replacing UTF-8 by whatever encoding your byte[] is using to represent the text).
据我所知,没有更好的方法。并且您应该始终使用带有编码的构造函数,或者它几乎可以保证,如果您处理英语以外的任何语言,您最终会得到搞砸的字符。即:你真的应该使用new String(bytes, "UTF-8")
(显然用你的 byte[] 用来表示文本的任何编码替换 UTF-8)。
回答by Hasan Masud
String head=new String(byteArray, "ISO-8859-1");
String head=new String(byteArray, "ISO-8859-1");