Java IntelliJ";FileNotFoundException“;,文件存在

Java IntelliJ";FileNotFoundException“;,文件存在,java,intellij-idea,filenotfoundexception,Java,Intellij Idea,Filenotfoundexception,我的目标是读取IntelliJ上的文本文件。 但是,当我运行代码时,会收到一条“FileNotFoundException”消息。我的文件存在。我三次检查以确保路径正确。我已经搜索了Stack Overflow以寻找答案,阅读了我遇到的每个问题,但没有人提供具体的解决方案 这是我的代码: import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import jav

我的目标是读取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();
           }
       }
    }
这是显示的错误消息

    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

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

System.out.println(new File("input.txt").getAbsolutePath());
然后,由于您使用的是IntelliJ,所以可以在IDE中打开terminal,并尝试从那个里打开此文件。例如:

cat /Users/antonpp/Documents/Projects/testapp/input.txt

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

哦,关于这一点,我也有一些问题。因此,请尝试编辑配置。您可以在运行->编辑配置中找到它。。然后将
工作目录
编辑到文件所在的位置。顺便说一句,您可以将其编辑到基本目录并在代码中添加路径。

问题是因为工作目录不同,即源代码所在的目录与IntelliJ的当前工作目录不同。通常,工作目录是项目的主目录。
因此,要么将文件放在该目录中,要么使用
编辑配置…
选项。选择
编辑配置…
后,检查选项
工作目录
,并相应地更改它。

很可能
输入数据
没有指向您认为它指向的文件。尝试使用绝对路径,或者只是尝试打印
inputData
的绝对路径,然后查看输出是什么。打印
System.getProperty(“user.dir”)
并查看该目录是否就是文件所在的目录。如果没有,请使用
getAbsolutePath()
I获得了绝对路径,并且文件确实存在,但仍然显示错误消息:(您确定文件扩展名没有弄乱吗?Windows中有几次文件扩展名对于已知类型是隐藏的。请尝试使用您的程序列出各个目录中的所有文件,并查看它是否列出输入。txt@Jack我检查了目录,它列为“文件输入”在我运行程序之后,我得到了绝对路径,并弹出了相同的错误消息。
cat /Users/antonpp/Documents/Projects/testapp/input.txt