为什么我的程序在文件存在时捕获/抛出FileNotFoundException?

Java新手在这里!

我正在编写一个程序来练习读取输入和将输出写入文件。 我已经完成了程序的编码,但是当我运行它时,程序只是捕获并继续FileNotFoundException。

该文件位于程序的源文件夹中,我甚至尝试将其放在与程序相关的每个文件夹中。 我试过了:

  • 声明方法标头中的exception
  • 使用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); 

答案很简单。 如果您收到FilENotFoundException ,显然原因是给定路径中找不到File。
如果使用IDE,则工作目录的路径与源目录不同。
例如,如果您使用的是NetBeans,则源文件位于/src 。 但是您的工作目录( . )是项目目录。
另一方面,问题可能是@Don提到的问题。 如果您要采用跨平台方法,则可以在路径中使用“ / ”。 它与OS无关。
示例: String fileName = "C:/Directory/File.txt";
这些路径区分大小写。 因此,请确保使用正确的案例。 (在打包程序之前,在Windows中不会出现问题。)