让我们假设我刚刚使用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;
}
要转换utf-8数据,不能假设字节和字符之间是1-1对应关系。
试试这个:
String file_string = new String(bytes, "UTF-8");
(呸呸呸。我发现我在点击“发布你的答案”按钮时慢了很多。)
要将整个文件读取为字符串,可以这样做:
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
}
}
}