IntelliJ“ FileNotFoundException”,文件存在

Sug*_*der 6 java filenotfoundexception intellij-idea

我的目标是在IntelliJ上读取文本文件。但是,当我运行代码时,收到“ FileNotFoundException”消息。我的文件存在。我仔细检查了一下,以确保路径正确。我一直在寻找Stack Overflow的答案,阅读我遇到的每个问题,但是没有人提供具体的解决方案。

这是我的代码:

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;


    public class LetterGrader {

        public static void main(String[] args) {

           String curDir = new File(".").getAbsolutePath();
           System.out.println("Current sys dir: " + curDir);


           try {
               File inputData = new File("input.txt");
               BufferedReader br = new BufferedReader(new FileReader(inputData));

           } catch (IOException e) {
               System.out.println("File not found");
               e.printStackTrace();
           }
       }
    }
Run Code Online (Sandbox Code Playgroud)

这是显示的错误消息。

    File not found
    java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
        at java.io.FileInputStream.open0(Native Method)
        at java.io.FileInputStream.open(FileInputStream.java:195)
        at java.io.FileInputStream.<init>(FileInputStream.java:138)
        at java.io.FileReader.<init>(FileReader.java:72)
        at LetterGrader.main(LetterGrader.java:23)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

    Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!找到解决方案后,我也会回覆。

[更新]

我通过将“ input.txt”文件移出或将src文件夹移入主项目的文件夹来解决了该问题。

我还使用了Scanner而不是BufferedReader。

我的最终代码有效:

        try {
            Scanner diskScanner = new Scanner(new File("input.txt"));
            while (diskScanner.hasNextLine()) {
                System.out.println(diskScanner.nextLine());
            }
            diskScanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
Run Code Online (Sandbox Code Playgroud)

Dev*_*rya 6

问题是因为工作目录不同,即你的源代码所在的目录和当前工作目录IntelliJ不同。通常,工作目录是项目的主目录。因此,要么将文件放在该目录中,要么使用Edit Configurations...选项。选择后Edit Configurations...,检查该选项Working directory并相应地更改它。


ant*_*npp 3

您可以先尝试打印文件的绝对路径

System.out.println(new File("input.txt").getAbsolutePath());
Run Code Online (Sandbox Code Playgroud)

然后,由于您使用的是 IntelliJ,因此您可以直接在 IDE 中打开终端并尝试从那里打开该文件。例如:

cat /Users/antonpp/Documents/Projects/testapp/input.txt
Run Code Online (Sandbox Code Playgroud)

因此,您将完全确定该文件存在并且位于正确的位置。