2
Java新手在这里!为什么我的程序在文件存在时捕获/抛出FileNotFoundException?
我正在写一个程序来练习阅读输入和写入输出到文件。我已经完成了对程序的编码,但是当我运行它时,程序会捕获并继续执行FileNotFoundException。
该文件位于该程序的源文件夹中,我甚至尝试将它放在与该程序相关的每个文件夹中。我已经试过:
- 声明的方法头
- 周边的部分功能于问题与try/catch块的异常。
- 以上两者在一起。
下面是导致问题的相关代码。有什么突出的,我失踪了?
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
String playerHighestScore = "", playerLowestScore = "";
int numPlayers = 0, scoreHighest = 0, scoreLowest = 0;
System.out.println("Enter an input file name: ");
String inputFileName = keyboard.nextLine();
String outputFileName = getOutputFileName(keyboard, inputFileName);
File inputFile = new File(inputFileName);
try {
Scanner reader = new Scanner(inputFile);
reader.close();
}
catch (FileNotFoundException exception) {
System.out.println("There was a problem reading from the file.");
System.exit(0);
}
Scanner reader = new Scanner(inputFile);
PrintWriter writer = new PrintWriter(outputFileName);
为了更快地获得更好的帮助,请发布[SSCCE](http://sscce.org/)。顺便说一句 - 沿着'File f = new File(“。”)的方向在该方法中进行一些调试。 System.out.println(f.getCanonicalPath());'并检查它指向你期望的位置。 – 2013-04-20 04:16:12
我几乎肯定它与路径有关。这是什么操作系统,你是否逃避斜线(Windows的反斜杠,否则正斜杠)? (例如C:\ Some Directory \ file.txt是错误的,它应该是** C \\:某个目录\\ file.txt)** – Don 2013-04-20 04:31:13
另外,由于您刚开始时,我建议使用固定一个用于测试程序的String对象,而不是手工输入(例如'String file =“C:\\ Some Directory \\ file.txt”;'比您进入控制台的东西更容易发现错误路径很容易弄乱,因为每当你手工输入时,它就会让事情变得更容易,但这只是我的看法而已,我不想阻止你试验因为这就是你学习的方式。 – Don 2013-04-20 04:36:33