UTF-8 byte []到String
问题描述:
假设我刚刚使用 BufferedInputStream
将UTF-8编码的文本文件的字节读入字节数组。我知道我可以使用以下例程将字节转换为字符串,但有没有比仅仅迭代字节并转换每个字节更有效/更智能的方法呢?
Let's suppose I have just used a BufferedInputStream
to read the bytes of a UTF-8 encoded text file into a byte array. I know that I can use the following routine to convert the bytes to a string, but is there a more efficient/smarter way of doing this than just iterating through the bytes and converting each one?
public String openFileToString(byte[] _bytes)
{
String file_string = "";
for(int i = 0; i < _bytes.length; i++)
{
file_string += (char)_bytes[i];
}
return file_string;
}
答
查看字符串
String str = new String(bytes, StandardCharsets.UTF_8);
如果你感到懒惰,你可以使用 Apache Commons IO 库直接将InputStream转换为String:
And if you're feeling lazy, you can use the Apache Commons IO library to convert the InputStream to a String directly:
String str = IOUtils.toString(inputStream, StandardCharsets.UTF_8);