从Text文件读取并解析为ArrayList

时间:2018-02-27 18:51:24

标签: java parsing arraylist

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

的问题

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

我通过调试器看到String[] words大小为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();
} 

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

2 个答案:

答案 0 :(得分:1)

您可以使用Java 8中的流。我认为使用pattern with groups更简单的是简单的分割字符串:

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());
}

或者您只需在代码中添加total words检查:

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

    if(words.length < 5)
        continue;

    // ...
}

答案 1 :(得分:0)

使用Scanner类怎么样?

import java.io.*;
import java.time.*;

try (Scanner reader = new Scanner (new File ("bill.txt"))) {
    while (reader.hasNextLine()) {
        reader.useDelimiter ("[ \t\n]");
        Integer id = reader.nextInt ();
        String venName = reader.next ();
        Double amount = reader.nextDouble ();
        LocalDate date = LocalDate.parse (reader.next ());
//      Don't know about BillType class
        String bt = reader.next ();
//      Don't have Bill.class
//      list.add(new Bill (venName, amount, date, bt, id));
    }
} catch (IOException e) {
    e.printStackTrace();
}