BufferedReader读取文件内容中文乱码问题及解决方案
程序员文章站
2022-04-15 23:13:45
问题代码:使用该代码读取文件内容时,bufferedReader会以系统默认的编码字符集获取文件内容。如果解析设置的编码字符集与系统默认编码字符集不一致,则会出现乱码问题。File file = new File("D:/1.txt");BufferedReader br = null;try { br = new BufferedReader(new FileReader(file));String tmpStr = null;while ((tmpStr=br.readLine())!...
问题代码:使用该代码读取文件内容时,bufferedReader会以系统默认的编码字符集获取文件内容。如果解析设置的编码字符集与系统默认编码字符集不一致,则会出现乱码问题。
File file = new File("D:/1.txt");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String tmpStr = null;
while ((tmpStr=br.readLine())!=null) {
byte[] tmpByte = tmpStr.getBytes(Charset.forName("GBK"));
String name = new String(tmpByte,0,10,Charset.forName("GBK"));
String birthday = new String(tmpByte,10, 8,Charset.forName("GBK"));
String sex = new String(tmpByte,18, 1,Charset.forName("GBK"));
System.out.println(name+";"+birthday+";"+sex);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
修改后的代码:在获取文件流时,设置文件的编码字符集,这样在解析的时候才能正常解析。
File file = new File("D:/1.txt");
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file),Charset.forName("GBK")));
String tmpStr = null;
while ((tmpStr=br.readLine())!=null) {
byte[] tmpByte = tmpStr.getBytes(Charset.forName("GBK"));
String name = new String(tmpByte,0,10,Charset.forName("GBK"));
String birthday = new String(tmpByte,10, 8,Charset.forName("GBK"));
String sex = new String(tmpByte,18, 1,Charset.forName("GBK"));
System.out.println(name+";"+birthday+";"+sex);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
本文地址:https://blog.csdn.net/weixin_43652442/article/details/107340848