【问题标题】:Why is my program catching / throwing a FileNotFoundException when the file exists?为什么我的程序在文件存在时捕获/抛出 FileNotFoundException?
【发布时间】:2013-04-20 04:10:25
【问题描述】:

这里是 Java 新手!

我正在编写一个程序来练习读取输入并将输出写入文件。我已经完成了程序的编码,但是当我运行它时,程序只是捕获并继续执行 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。顺便说一句 - 按照File f = new File("."); System.out.println(f.getCanonicalPath()); 的行在该方法中进行一些调试,并检查它指向您期望的位置。
  • 我几乎可以肯定它与路径有关。这是在什么操作系统上运行,您是否正在转义斜杠(Windows 为反斜杠,否则为正斜杠)? (例如 C:\Some Directory\file.txt 是错误的。应该是 C\\:Some Directory\\file.txt)
  • 另外,由于您刚刚开始,我建议您在测试程序中使用固定的 String 对象,而不是手动输入(例如 String file = "C:\\Some Directory\\file.txt"; 会更容易发现错误in 而不是你在控制台中输入的东西。路径很容易弄乱,而且,当你每次手动输入时,它更容易弄乱。但是,这只是我的看法。我不不想阻止你尝试,因为那是你学习的方式。

标签: java exception runtime-error filenotfoundexception


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    相关资源
    最近更新 更多