UTF-8 字节 [] 到字符串 [英] UTF-8 byte[] to String

查看:45
本文介绍了UTF-8 字节 [] 到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我刚刚使用了 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

String str = new String(bytes, StandardCharsets.UTF_8);

如果您觉得懒惰,可以使用 Apache Commons IO 库来转换InputStream 直接转为字符串:

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);

这篇关于UTF-8 字节 [] 到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆