简体   繁体   中英

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

Java newbie here!

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.

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.
  • 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.
If you use an IDE, path for the working directory is different from the source directory.
For example, if you are using NetBeans, your source files are inside /src . But your working directory ( . ) is the project directory.
In the other hand, the problem may be the thing that @Don mentioned. 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";
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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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