【发布时间】:2017-10-19 23:05:06
【问题描述】:
这是同一方法的两个版本。第一个使用 JOptionPane,第二个使用控制台。他们应该从用户输入中获取文件路径(字符串)来查找文件并读取它。
第一种方法工作得很好,但是使用控制台的第二种方法给了我一个 FileNotFoundException 错误。如果它们几乎相同,为什么第二个不起作用?
//使用 JOptionPane ///////////////////////////////////////// /////////////
public void addFromFile() {
String[] option1 = { "Go back to Main Manu", "Continue" };
int choice4 = JOptionPane.showOptionDialog(null,
"Warning: this method will delete existing data before it add file data", "Monster Database",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, option1, null);
if (choice4 == 0)
monitor();
if (choice4 == 1) {
monsterAttackList.clear();
Scanner input = new Scanner(System.in);
String filePath = JOptionPane.showInputDialog(null, "Enter a filepath");
File inFile = new File(filePath);
try {
Scanner fileReader = new Scanner(inFile);
String line;
String[] part;
int attackID;
String monster;
String date;
String location;
String reporter;
while (fileReader.hasNextLine()) {
line = fileReader.nextLine();
part = line.split(",");
attackID = Integer.parseInt(part[0]);
monster = part[1];
date = part[2];
location = part[3];
reporter = part[4];
monsterAttackList.add(new MonsterAttack(attackID, monster, date, location, reporter));
}
fileReader.close(); // Close to unlock.
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "filepath is not valid");
System.err.println(e);
}
}
}
// 使用扫描仪 ///////////////////////////////////////// //////////////////////
public void addFromFile() {
System.out.println("Warning: this method will delete existing data before it add file data");
System.out.println("\n1. Go back to Main Manu" + "\n2. Continue \n");
Scanner input = new Scanner(System.in);
int choice4 = input.nextInt();
if (choice4 == 1)
monitor();
if (choice4 == 2) {
monsterAttackList.clear();
System.out.println("Enter a filepath");
String filePath = input.nextLine();
File inFile = new File(filePath);
try {
Scanner fileReader = new Scanner(inFile);
String line;
String[] part;
int attackID;
String monster;
String date;
String location;
String reporter;
while (fileReader.hasNextLine()) {
line = fileReader.nextLine();
part = line.split(",");
attackID = Integer.parseInt(part[0]);
monster = part[1];
date = part[2];
location = part[3];
reporter = part[4];
monsterAttackList.add(new MonsterAttack(attackID, monster, date, location, reporter));
}
fileReader.close(); // Close to unlock.
input.close();
} catch (IOException e) {
System.out.println("filepath is not valid");
System.err.println(e);
}
}
}
【问题讨论】:
标签: java csv exception console filereader