UTF-8 byte []到String

时间:2011-12-14 21:46:11

标签: java utf-8

假设我刚刚使用BufferedInputStream将UTF-8编码的文本文件的字节读入字节数组。我知道我可以使用以下例程将字节转换为字符串,但是这样做是否有更高效/更智能的方法,而不仅仅是迭代字节并转换每个字节?

public String openFileToString(byte[] _bytes)
{
    String file_string = "";

    for(int i = 0; i < _bytes.length; i++)
    {
        file_string += (char)_bytes[i];
    }

    return file_string;    
}

11 个答案:

答案 0 :(得分:481)

查看String

的构造函数
String str = new String(bytes, StandardCharsets.UTF_8);

如果您感到懒惰,可以使用Apache Commons IO库直接将InputStream转换为String:

String str = IOUtils.toString(inputStream, StandardCharsets.UTF_8);

答案 1 :(得分:39)

Java String类有一个内置构造函数,用于将字节数组转换为字符串。

byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};

String value = new String(byteArray, "UTF-8");

答案 2 :(得分:9)

要转换utf-8数据,您不能假设字节和字符之间有1-1对应关系。 试试这个:

String file_string = new String(bytes, "UTF-8");

(呸。我看到我按“发布你的答案”按钮放慢了速度。)

要将整个文件读取为String,请执行以下操作:

public String openFileToString(String fileName) throws IOException
{
    InputStream is = new BufferedInputStream(new FileInputStream(fileName));

    try {
        InputStreamReader rdr = new InputStreamReader(is, "UTF-8");
        StringBuilder contents = new StringBuilder();
        char[] buff = new char[4096];
        int len = rdr.read(buff);
        while (len >= 0) {
            contents.append(buff, 0, len);
        }
        return buff.toString();
    } finally {
        try {
            is.close();
        } catch (Exception e) {
            // log error in closing the file
        }
    }
}

答案 3 :(得分:4)

您可以使用String(byte[] bytes)构造函数。有关详细信息,请参阅此link编辑您还必须根据java doc来考虑平台的默认字符集:

  

通过使用解码指定的字节数组构造一个新的String   平台的默认字符集。新String的长度是a   charset的功能,因此可能不等于长度   字节数组。给定字节时此构造函数的行为   在默认情况下charset中无效是未指定的。该   当更多控制时,应该使用CharsetDecoder类   解码过程是必需的。

答案 4 :(得分:2)

知道您正在处理UTF-8字节数组,您肯定希望使用String constructor that accepts a charset name。否则,您可能会对基于charset编码的安全漏洞敞开心扉。请注意,它会抛出您必须处理的UnsupportedEncodingException。像这样:

public String openFileToString(String fileName) {
    String file_string;
    try {
        file_string = new String(_bytes, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // this should never happen because "UTF-8" is hard-coded.
        throw new IllegalStateException(e);
    }
    return file_string;
}

答案 5 :(得分:2)

您可以使用此问题中描述的方法(特别是在您开始使用InputStream时):Read/convert an InputStream to a String

特别是,如果您不想依赖外部库,可以尝试this answerInputStream通过InputStreamReader读取char[]缓冲区并将其附加到StringBuilder

答案 6 :(得分:2)

这是一个简化的函数,它将以字节为单位读取并创建一个字符串。它假设您可能已经知道该文件的编码方式(以及默认值)。

static final int BUFF_SIZE = 2048;
static final String DEFAULT_ENCODING = "utf-8";

public static String readFileToString(String filePath, String encoding) throws IOException {

    if (encoding == null || encoding.length() == 0)
        encoding = DEFAULT_ENCODING;

    StringBuffer content = new StringBuffer();

    FileInputStream fis = new FileInputStream(new File(filePath));
    byte[] buffer = new byte[BUFF_SIZE];

    int bytesRead = 0;
    while ((bytesRead = fis.read(buffer)) != -1)
        content.append(new String(buffer, 0, bytesRead, encoding));

    fis.close();        
    return content.toString();
}

答案 7 :(得分:1)

String有一个构造函数,它将byte []和charsetname作为参数:)

答案 8 :(得分:0)

这也涉及迭代,但这比连接字符串要好得多,因为它们非常昂贵。

public String openFileToString(String fileName)
{
    StringBuilder s = new StringBuilder(_bytes.length);

    for(int i = 0; i < _bytes.length; i++)
    {
        s.append((char)_bytes[i]);
    }

    return s.toString();    
}

答案 9 :(得分:0)

为什么不从get go中获取你想要的东西并从文件中读取一个字符串而不是一个字节数组?类似的东西:

BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream( "foo.txt"), Charset.forName( "UTF-8"));

然后从里面读取直到它完成。

答案 10 :(得分:0)

我用这种方式

String strIn = new String(_bytes, 0, numBytes);