Java 扫描仪(System.in)在用户输入后不打开文件

Java Scanner(System.in) does not open file after user input

您好,我遇到了一个问题,但我找不到解决方案。我要求用户输入文件名,但我得到的输出始终是“'unable to open file'”。任何建议将不胜感激。

    Scanner reader = new Scanner(System.in); 
    System.out.println("Enter the name of textfile to be read ( add .txt): ");

    String fileName = reader.next();
    String line = null;
    BufferedReader bufferedReader =   new BufferedReader(fileReader);

    while((line = bufferedReader.readLine()) != null) {
        System.out.println(line); 

        catch(FileNotFoundException ex) {
        System.out.println(
            "Unable to open file '" + 
            fileName + "'");                
       }

        catch(IOException ex) {
        System.out.println(
            "Error reading file '" 
            + fileName + "'");                  
        // Or we could just do this: 
        // ex.printStackTrace();
    }
    }

FileNotFoundException 总是被执行,但为什么?

P.S 如果我将路径更改为特定位置,例如 "C:\etc",它会读取文件。

如果只给文件名不给路径,Java不知道去哪里找。如果您确定该文件将位于项目目录中,只需将 C:/etc 添加到用户输入中。

如果您不指定绝对文件路径,即 C:/dir/...,java 将查找与项目根目录相同的目录(与您的 src 相同的目录和 bin 个文件夹)。如果文件在那里,它将仅通过文件名找到它,或者如果您在该文件夹中创建目录,则路径中需要该目录。如果您有一个可执行 JAR,情况也是如此,它将在 JAR 所在的同一目录中查找。