gpt4 book ai didi

java - 尝试允许用户使用扫描仪选择文本文件

转载 作者:行者123 更新时间:2023-12-01 11:44:13 25 4
gpt4 key购买 nike

正如标题所示,我试图允许用户输入他们想要选择的文件的名称,以便我的程序分析该文本文件。但是,当我输入文本文件的名称(即“test.txt”)时,我收到文件未找到错误,该文件与类位于同一目录中,这就是为什么我很困惑为什么它不存在工作,有人可以帮助解释我在这里做错了什么吗?

这是我的代码:

   Scanner in = new Scanner(System.in);
System.out.print("Enter filename: ");
String filename = in.nextLine();
File InputFile = new File(filename);

Scanner reader = new Scanner(InputFile);

错误:

Enter filename: test.txt //Here is what I have entered after being prompted.
Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified)

谢谢!

最佳答案

如何处理FileNotFoundException

  1. If the message of the exception claims that there is no such file or directory, then you must verify that the specified is correct and actually points to a file or directory that exists in your system.

  2. If the message of the exception claims that permission is denied then, you must first check if the permissions of the file are correct and second, if the file is currently being used by another application.

  3. If the message of the exception claims that the specified file is a directory, then you must either alter the name of the file or delete the existing directory (if the directory is not being used by an application).

重要:

For those developers that use an IDE to implement their Java applications, the relative path for every file must be specified starting from the level where the src directory of the project resides.

注意:您的问题是选项一。

我该如何解决这个问题?

  1. 我通常使用绝对路径,但我不推荐,因为这只是米奇老鼠的工作。

  2. 使用相对路径,因为您的程序将与路径无关。

关于java - 尝试允许用户使用扫描仪选择文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29285439/

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