在字符流读取文件时发现读取出现了中文乱码
代码:
public class test1 {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("e:\\a1\\d1.txt"));
String s=null;
while((s=br.readLine())!=null){
System.out.println(s);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
效果:
txt文本创建采用的编码是ANSI的编码方式,而字符流读取时是以utf-8读的。
解决方式
方式一1.通过转化流 InputStreamReader,用GBK的方式来读
public class test1 {
public static void main(String[] args) {
try {
//看这里
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("e:\\a1\\d1.txt"),"GBK"));
String s=null;
while((s=br.readLine())!=null){
System.out.println(s);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
方式二
将文件以utf-8的方式另存为,这样也能解决中文乱码