27.13解决乱码问题
27.13.1字符输入流读取乱码
如下代码Test09_01,原本a.txt文件时UTF-8
,运行Test09_01不会出先乱码,现在将a.txt文件改成GBK
格式,再运行Test09_01代码读取文件内容时会出现乱码。
public class Test09_01 {
public static void main(String[] args) {
// 创建字符输入流对象
Reader fr = null;
try {
fr = new FileReader("code_java02\\a.txt");
// 记录读取的汉字解码后的十进制数
int ch;
// 循环读取
while ((ch = fr.read()) != -1){
// System.out.println(ch);十进制数
System.out.print((char) ch);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
// 释放资源
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
解决乱码:
方案一:
创建字符输入流对象时候,不创建FileReader对象用Reader接收,而是创建字符转换输入流:InputStreamReader(字节流InputStream,编码)的对象用Reader接收,这样可以在里面指定编码方式,即将编码方式设置成和文本文件编码方式一致即可。FileReader对象的方法中不能指定编码方式。
该进后代码如Test09_02下:
方案二:
直接将文本文件编码方式改成和idea编码方式一致。
public class Test09_02 {
public static void main(String[] args) {
// public int read() 读取数据,读到末尾返回-1
// 创建字符输入流对象
Reader fr = null;
// 创建字节输入流对象
FileInputStream fis = null;
try {
fis = new FileInputStream("code_java02\\a.txt");
fr = new InputStreamReader(fis,"GBK");
// 记录读取的汉字解码后的十进制数
int ch;
// 循环读取
while ((ch = fr.read()) != -1){
// System.out.println(ch);十进制数
System.out.print((char) ch);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
// 释放资源
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}