【问题标题】:Weird BufferedReader behavior for a huge file巨大文件的奇怪 BufferedReader 行为
【发布时间】:2015-05-14 09:34:01
【问题描述】:

我遇到了一个非常奇怪的错误。所以,我的程序读取了一个 csv 文件。

每当谈到这一行:

"275081";"cernusco astreet, milan, italy";NULL

我收到一个错误:

在调试屏幕中,我看到 BufferedReader 只读

"275081";"cernusco as

这是该行的一部分。但是,它应该读取所​​有行。

最让我烦恼的是,当我从 csv 文件中删除该行时,错误就消失了!该程序运行没有任何问题。我可以删除该行,也许这是一个错误的输入或其他什么;但是,我想了解我为什么会遇到这个问题。

为了更好地理解,我将在此处包含我的部分代码:

        reader = new BufferedReader(new FileReader(userFile));
        reader.readLine(); // skip first line
        while ((line = reader.readLine()) != null) {
            String[] fields = line.split("\";\"");
            int id = Integer.parseInt(stripPunctionMark(fields[0]));
            String location = fields[1];
            if (location.contains("\";")) { // When there is no age. The data is represented as "location";NULL. We cannot split for ";" here. So check for "; and split.
                location = location.split("\";")[0];
                System.out.printf("Added %d at %s\n", id, location);
                people.put(id, new Person(id, location));
                numberOfPeople++;
            }
            else {
                int age = Integer.parseInt(stripPunctionMark(fields[2]));
                people.put(id, new Person(id, location, age));
                System.out.printf("Added %d at: %s age: %d \n", id, location, age);
                numberOfPeople++;
            }

另外,您可以找到 csv 文件 here 或者这里是我遇到错误的部分的简短版本:

"275078";"el paso, texas, usa";"62"
"275079";"istanbul, eurasia, turkey";"26"
"275080";"madrid, n/a, spain";"29"
"275081";"cernusco astreet, milan, italy";NULL
"275082";"hacienda heights, california, usa";"16"
"275083";"cedar rapids, iowa, usa";"22"

【问题讨论】:

  • 你试过用有效的字符串代替“NULL”吗?
  • 我只是将行改为:"275081";"cernusco as treet, milan, italy";"15" 但问题仍然存在。在这一行之前有很多 NULL。而且,我的程序处理得很好。只是这句特别的台词让我发疯了。
  • as后面好像有个隐藏字符。您可以提取文件的那部分并使用十六进制转储查看它吗?
  • 用十六进制编辑器查看文件——那行有什么奇怪的字符吗?
  • 第 44 行是哪一行?文件底部有空行吗?

标签: java string csv split


【解决方案1】:

这与BufferedReader. 没有任何关系,它甚至不会出现在堆栈跟踪中。

这与您未能检查 String.split(). 返回的数组的结果和长度有关,相反,您只是假设输入格式正确,每行至少包含三列,并且您没有防御措施如果不是。

【讨论】:

  • 是否有一个 Java 库可以为我们完成所有这些事情?例如,只需输入一个文件,它就会给出一个 Map 或 Arrays。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-13
  • 2019-12-21
  • 1970-01-01
  • 2012-11-04
  • 2023-03-12
相关资源
最近更新 更多