java - 从文本文件中读取并解析为ArrayList

标签 java parsing arraylist

解决添加 if (line.isEmpty()) continue;

我需要从文本文件中读取数据并将这些数据添加到我的 ArrayList 中。

我通过调试器看到String[]字大小为1,即""。 这就是为什么我遇到异常:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)

我的代码是

List<Bill> list = new ArrayList<>();

try (BufferedReader reader = new BufferedReader(new FileReader("bill.txt"))) {
    String line;

    while ((line = reader.readLine()) != null) {
        String[] words = line.split(" ");
        Integer id = Integer.parseInt(words[0]);
        String venName = words[1];
        Double amount = Double.parseDouble(words[2]);
        LocalDate date = LocalDate.parse(words[3]);
        BillType bt = BillType.valueOf(words[4]);
        list.add(new Bill(venName, amount, date, bt, id));
    }
} catch(IOException e) {
    e.printStackTrace();
} 

在此作业中,我无法使用文件和对象输入/输出流。
你能帮我修复这个错误吗?

最佳答案

您可以使用 Java 8 中的流。我认为使用模式与组比简单的分割字符串更清晰:

private static final Pattern WORDS = Pattern.compile("(?<id>\\d+)\\s+(?<name>[^\\s]+)\\s+(?<amount>[^\\s]+)\\s+(?<date>[^\\s]+)\\s+(?<type>[^\\s]+)");

public static List<Bill> readBillFile(String fileName) throws IOException {
    return Files.lines(Paths.get(fileName))
                .map(WORDS::matcher)
                .filter(Matcher::matches)
                .map(matcher -> {
                    int id = Integer.parseInt(matcher.group("id"));
                    String venName = matcher.group("name");
                    double amount = Double.parseDouble(matcher.group("amount"));
                    LocalDate date = LocalDate.parse(matcher.group("date"));
                    BillType bt = BillType.valueOf(matcher.group("type"));
                    return new Bill(venName, amount, date, bt, id);
                })
                .collect(Collectors.toList());
}

或者您可以在代码中添加对总字数的检查:

while ((line = reader.readLine()) != null) {
    String[] words = line.split(" ");

    if(words.length < 5)
        continue;

    // ...
}

关于java - 从文本文件中读取并解析为ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49015938/

相关文章:

java - 在 Java 中从 ArrayList<ArrayList<Integer>> 输出整数

java - 如何构建一个可以捕获用户输入并生成可打印输出的简单应用程序

python - 从字典中将指定的键值加载到 json 对象中

python - 如何删除列表列表中的最后一个元素?

Java 木瓦对

java - 在 Eclipse Debugger 中,获取嵌入列表层次结构中变量的索引位置

java - Java中广泛使用的哈希算法用于实现哈希表?

java - 如何在 Java 中从 Share 调用 Alfresco(存储库)网页脚本

java - 我想在将json传递给我的服务时创建BPMN工作流图

java - 在antlr4中向Lexer/Parser文件添加自定义异常的正确方法