让我们假设我刚刚使用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;
}
下面是一个简化的函数,它将读取字节并创建字符串。它假定您可能已经知道文件的编码(否则为默认值)。
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();
}
要转换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
}
}
}