欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java读取txt文件第一行遇到的问题

程序员文章站 2024-03-04 15:32:29
...

场景:

今天在用java字符流读取类似下图的txt文件:

java读取txt文件第一行遇到的问题

目标是将每一行的内容通过’,’分割,分别转化为int和String类型并保存,读取代码如下:

File file = new File("C:\\Users\\liuwi\\Desktop\\百度城市信息.txt");
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file));
            String temp = null;
            List<City> cities = new ArrayList<>();
            while ((temp = reader.readLine()) != null){
                String[] result = temp.split(",");
                City city = new City();
                String cityId = result[0];
                city.setAreaId(Integer.parseInt(result[0]));
                city.setName(result[1]);
                                cities.add(city);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

逻辑上来看没什么问题,运行一下,报错:
java读取txt文件第一行遇到的问题
错误信息:33转换为int失败。很奇怪,开始以为是字符中包含空格,但是用trim()处理了还是同样的结果,因此我将split后的每个字符都输出:

String[] result = temp.split(",");
char[] cityIdChar = result[0].toCharArray();
for(int i = 0; i < cityIdChar.length; i++){
    System.out.println("out:" + cityIdChar[i]);
}

debug的结果:
java读取txt文件第一行遇到的问题
控制台输出的结果:
java读取txt文件第一行遇到的问题
可以看到cityIdChar并不是我们想象中的{3, 3},而是{, 3, 3},数组的第一个位置多了一个未知的占位符

原因

该txt文件保存为UTF-8字符集,一般在文件头部会有BOM编码,该编码标识了这个文件是一个UTF-8文件,而jdk8在处理UTF-8文件可以看出Java在读文件时没能正确处理UTF-8文件的BOM编码,输出了一个空字符

解决办法

1、将txt文件保存为unicode字符集,因为java默认字符集为unicode
2、使用EditPlus等工具将txt文件另存为UTF-8无BOM格式

相关标签: java 字符流