不同编码格式下,一个中文汉字的字节数是不一样的,以UTF-8格式的“应”字为例,其占字节数为3。
假设文本文件中的内容就由五个"应"子构成(UTF-8格式),其所占的字节数就是15。此时如果声明一个FileInputStream对象,并用byte[] bytes = new byte[10](一般是1024)进行读取,前三个"应"字可以正常读取,第四个"应"字就会被截断而导致乱码,第五个"应"字因为进入了下一次循环,则不会乱码。
//TODO 会出现乱码
FileInputStream input = new FileInputStream(new File("filePath"));
byte[] bytes = new byte[10];
while(input.read(bytes) != -1){
System.out.println(new String(bytes));
}
采用BufferReader可以避免乱码的情况。
try {
fis = new FileInputStream("filePath");
InputStreamReader reader = new InputStreamReader(fis,"UTF-8");
BufferedReader br = new BufferedReader(reader);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}