尝试允许用户 select 使用扫描仪的文本文件

Trying to allow a user to select a text file using a Scanner

正如标题所说,我试图让用户输入他们想要 select 的文件的名称,以便我的程序分析该文本文件。 但是,当我输入文本文件的名称 "test.txt" 时,我收到一个文件未找到错误,该文件与 class 在同一目录中,这就是为什么我很困惑为什么它不起作用,有人可以帮助解释我在这里做错了什么吗?

这是我的代码:

   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)

谢谢!

来自 java 文档:

public 扫描器(文件来源) 抛出 FileNotFoundException

构造一个新的 Scanner,生成从指定文件扫描的值。使用底层平台的默认字符集将文件中的字节转换为字符。

参数: source - 要扫描的文件 投掷: FileNotFoundException - 如果未找到源

你应该打电话给

InputFile.createNewFile();

之前

 Scanner reader = new Scanner(InputFile);

如何处理 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. 使用相对路径因为你的程序将与路径无关。