【发布时间】:2018-11-24 07:22:32
【问题描述】:
我有一个方法可以读取包含 4 个部分的文本文件的部分内容:日期、名称、描述和数量,例如
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");
}
}
编辑: 取出最后的工作。
【问题讨论】:
-
您的文件存储在哪里?
filename的值是多少? -
我的文件存放在Intellij的src中,名字是expenses.txt
-
您正在关闭 Scanner,因为它读取了
finally中的第一行 -
@JoeyDeguzman :
filename的值是多少? -
您隐藏了异常类型、消息和堆栈跟踪,这会告诉您问题所在。不要捕捉异常。捕获您期望的异常,并且您可以正确处理。打印异常的堆栈跟踪。