gpt4 book ai didi

java - IntelliJ "FileNotFoundException",文件存在

转载 作者:行者123 更新时间:2023-12-03 18:13:03 25 4
gpt4 key购买 nike

我的目标是在 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

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

[更新]

我通过将我的“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();
}
}

最佳答案

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

关于java - IntelliJ "FileNotFoundException",文件存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33271744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com