为什么我的方法只读一行文字



我有一个方法,可以读取文本文件的四部分:日期、名称、描述和金额,就像一样

4/5/2018, gel, hair product, 20.00
4/4/2018, wax, hair product, 20.00

等等…

我的问题是,我的方法只读取第一行,然后输出catch方法,说找不到文件。

public static void showRecordedExpense(String filename)throws IOException {
String date = "";
String name = "";
String description = "";
double amount = 0.00;
try{
Scanner read = new Scanner(new File(filename));
while (read.hasNextLine()){
String oneLine = read.nextLine();
String[] parts = oneLine.split(",");
try {
date = parts[0];
name = parts[1];
description = parts[2];
amount = Double.parseDouble(parts[3]);
System.out.printf("%15s%15s%15s%20s%n", "---------------", "---------------",
"---------------", "---------------------");
System.out.printf("%15s%15s%15s%31s%n","Date", "Name", "Description","Amount");
System.out.printf("%15s%14s%33s%15s%n",date,name,description,amount);
System.out.printf("%15s%15s%15s%20s%n", "---------------", "---------------",
"---------------", "---------------------");
}catch (Exception e){
System.out.println("no");
} finally {
read.close();
}
}
}catch (Exception e){
System.out.println("The file could not be found");
}
}

编辑:取出最后工作的。

有关finally如何工作的详细信息,请阅读此处。由于finallytry/catch配对,您当前正在while循环第一次迭代结束时关闭扫描仪。while的下一次迭代由于您关闭了文件而无法再从中读取,这就是为什么它只读取第一行。考虑在while循环完成后取出finally并关闭扫描仪。

try{
Scanner read = new Scanner(new File(filename));
while (read.hasNextLine()){
String oneLine = read.nextLine();
String[] parts = oneLine.split(",");
try {
date = parts[0];
name = parts[1];
description = parts[2];
amount = Double.parseDouble(parts[3]);
System.out.printf("%15s%15s%15s%20s%n", "---------------", "---------------",
"---------------", "---------------------");
System.out.printf("%15s%15s%15s%31s%n","Date", "Name", "Description","Amount");
System.out.printf("%15s%14s%33s%15s%n",date,name,description,amount);
System.out.printf("%15s%15s%15s%20s%n", "---------------", "---------------",
"---------------", "---------------------");
}catch (Exception e){
System.out.println("no");
}
}
read.close();
}catch (Exception e){
System.out.println("The file could not be found");
}

最新更新