gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:03:42 25 4
gpt4 key购买 nike

这里是 Java 新手!

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

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

  • 在方法头声明异常
  • 用 try/catch block 围绕有问题的部分。
  • 以上两者一起。

这是导致问题的相关代码。有什么我遗漏的东西很突出吗?

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 提到的问题上。如果您打算采用跨平台方法,则可以在路径中使用“/”。无论操作系统如何,它都能正常工作。
示例:String fileName = "C:/Directory/File.txt";
并且这些路径区分大小写。因此,请确保使用正确的大小写。 (在您打包程序之前,这在 Windows 中不会成为问题。)

关于java - 为什么我的程序在文件存在时捕获/抛出 FileNotFoundException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16116469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com