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

标签 java file java.util.scanner

正如标题所示,我试图允许用户输入他们想要选择的文件的名称,以便我的程序分析该文本文件。 但是,当我输入文本文件的名称(即“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/

相关文章:

java - 检查输入到数组中的输入是否正确/不正确

java - 如何在 XSLT 中添加命名空间名称及其值?

java - Java获取当前月份的天数

java - Eclipse android项目不生成jar

r - 如何在没有用户交互的情况下更新与 R Shiny 中的 `fileInput` 变量相关的文件?

Java 文件列表未使用比较器排序

java - 如何在不使用科学记数法的情况下将字符串解析为 double

c# - 使用 .NET 删除目录中超过 3 个月的文件

java - 使用 Scanner 继续获取 NoSuchElementException

Java 将扫描仪传递给方法