Java读取UTF-8的txt文件第一行出现乱码“?”及解决
test.txt文件内容:
A中
2国
3
4
5
6
test.txt文件采用写字板保存为UTF-8格式
保存并关闭后使用写字板再次打开该UTF-8文档,中文、字母正常显示
测试代码:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class ReadTxtFile {
public static void main(String[] args) {
try {
String charsetName = "UTF-8";
String path = "D:/to_delete/test.txt";
File file = new File(path);
if (file.isFile() && file.exists())
{
InputStreamReader insReader = new InputStreamReader(
new FileInputStream(file), charsetName);
BufferedReader bufReader = new BufferedReader(insReader);
String line = new String();
while ((line = bufReader.readLine()) != null) {
System.out.println(line);
}
bufReader.close();
insReader.close();
}
} catch (Exception e) {
System.out.println("读取文件内容操作出错");
e.printStackTrace();
}
}
}
程序执行结果:
?A中
2国
3
4
5
6
我的解决办法:
使用UltraEdit将上边的txt文件另存为UTF-8无BOM格式;
或者
使用Notepad++打开上边的txt文件执行如下操作“格式-->以UTF-8无BOM格式编码”,修改后将txt文本进行保存。

本文探讨了Java读取UTF-8编码的TXT文件时出现乱码问题,尤其是在读取第一行含有中文字符的情况下。通过分析,发现问题是由于文件包含BOM(Byte Order Mark)导致的。文章提供了两种解决方案:一是使用UltraEdit将文件另存为UTF-8无BOM格式;二是使用Notepad++调整文件编码为UTF-8无BOM并保存。这些方法能有效避免读取时的乱码问题。
1001

被折叠的 条评论
为什么被折叠?



