ByteArrayOutputStream读取文件中文时乱码问题解决
当我们获取文件,通过输入流读取数据,并返回字符串回去
public String readFiles(String fileName){
FileInputStream inputStream = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String result = "";
try{
inputStream = openFileInput(fileName);
int len = 0;
byte[] date = new byte[4];
while ((len = inputStream.read(date)) != -1){
outputStream.write(date);
}
byte[] bytes = outputStream.toByteArray();
result = new String(bytes);
inputStream.close();
outputStream.close();
}catch (Exception e){
e.printStackTrace();
}
return result;
}
测试文件内容:
测试测试内容
测试情况:
测试测试内容��������������
乱码原因:
当编码为UTF-8时,汉字Java读入汉字占3~4个字节,在这里我们每个汉字占3个字节,那么6个汉字需要18个字节。
由于我们每次都读入4个字节,那么读取6次所产生的字节就是24个,多出来的字节自然就乱码了。
此时我们就需要将每次读取的数据的长度写入到缓冲区并拼接起来,而不是每次直接输出缓存的数据
代码如下:
public String readFiles(String fileName){
FileInputStream inputStream = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String result = "";
try{
inputStream = openFileInput(fileName);
int len = 0;
byte[] date = new byte[4];
while ((len = inputStream.read(date)) != -1){
//将每一次的数据写入缓冲区
outputStream.write(date,0,len);
}
byte[] bytes = outputStream.toByteArray();
result = new String(bytes);
inputStream.close();
outputStream.close();
}catch (Exception e){
e.printStackTrace();
}
return result;
}
测试结果:
测试测试内容