解决添加 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/