我的目标是在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();
}
}
inputData
指向的不是你认为的文件。尝试使用绝对路径或者直接打印inputData
的绝对路径并查看输出内容。 - user4668606System.getProperty("user.dir");
并查看目录是否为文件所在的目录。如果不是,则使用getAbsolutePath()
。 - sam