为什么我的程序在文件存在时捕获/抛出FileNotFoundException? [英] Why is my program catching / throwing a FileNotFoundException when the file exists?

查看:201
本文介绍了为什么我的程序在文件存在时捕获/抛出FileNotFoundException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java新手在这里!

Java newbie here!

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

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:


  • 在方法头中声明例外

  • 围绕截面 - / / $>
  • 这两个都在一起。

这里是导致问题的相关代码。有没有什么东西伸出来,我失踪了?

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


推荐答案

答案很简单。如果你得到一个 FilenotFoundException ,显然是给定路径中找不到文件的原因。
如果你使用IDE,工作目录的路径与源目录不同。

例如,如果您使用NetBeans,则源文件位于 / src 之内。但是你的工作目录()是项目目录。

另一方面,这个问题可能是@Don提到的。如果要进行跨平台方法,可以在路径中使用 / 。它的作用与OS无关。

示例: String fileName =C:/Directory/File.txt;

这些路径区分大小写。所以确保你使用正确的情况。 (Windows将不会出现问题,直到您打包程序。)

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

这篇关于为什么我的程序在文件存在时捕获/抛出FileNotFoundException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆