简体   繁体   English

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

[英]Why is my program catching / throwing a FileNotFoundException when the file exists?

Java newbie here! Java新手在这里!

I'm writing a program to practice reading input and writing output to files. 我正在编写一个程序来练习读取输入并将输出写入文件。 I've finished coding the program, but when I run it, the program just catches and proceeds with a FileNotFoundException. 我已经完成了对该程序的编码,但是当我运行它时,该程序只是捕获并继续执行FileNotFoundException。

The file is in the source folder for the program, and I've even tried placing it in every folder related to the program. 该文件位于程序的源文件夹中,我什至尝试将其放置在与该程序相关的每个文件夹中。 I've tried: 我试过了:

  • Declaring the exceptions in the method header 在方法标头中声明异常
  • Surrounding the section-in-question with a try/catch block. 用try / catch块包围所讨论的部分。
  • Both of the above together. 以上两者结合在一起。

Here's the relevant code that is causing problems. 这是引起问题的相关代码。 Is there something that sticks out that I'm missing? 有什么东西让我很想念吗?

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);

The answer is simple. 答案很简单。 If you get a FilENotFoundException , obviously the reason is File Not Found in the given path. 如果收到FilENotFoundException ,显然原因是给定路径中的File Not Found。
If you use an IDE, path for the working directory is different from the source directory. 如果使用IDE,则工作目录的路径与源目录不同。
For example, if you are using NetBeans, your source files are inside /src . 例如,如果您使用的是NetBeans,则源文件位于/src But your working directory ( . ) is the project directory. 但是您的工作目录( . )是项目目录。
In the other hand, the problem may be the thing that @Don mentioned. 另一方面,问题可能是@Don提到的问题。 If you are going for a cross platform approach, you can use " / " in paths. 如果您打算使用跨平台方法,则可以在路径中使用“ / ”。 It works irrespective to the OS. 它与操作系统无关。
Example : String fileName = "C:/Directory/File.txt"; 示例: String fileName = "C:/Directory/File.txt";
And these paths are case sensitive. 这些路径区分大小写。 So make sure you use the correct case. 因此,请确保使用正确的大小写。 (It won't be a problem in Windows, until you package the program.) (在Windows中,打包程序之前不会有问题。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM