【发布时间】:2016-01-21 04:25:02
【问题描述】:
我的目标是阅读 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的绝对路径并查看输出是什么。 -
打印
System.getProperty("user.dir");并查看目录是否是文件所在的目录。如果没有,请使用getAbsolutePath() -
我得到了绝对路径并且文件确实在那里,但仍然有错误消息。 :(
-
您确定文件扩展名没有弄乱吗?对于已知类型,Windows 文件扩展名很少被隐藏。尝试使用您的程序列出各个目录中的所有文件,看看它是否列出了 input.txt
-
@Jack 我检查了目录,在我运行程序后它列为“文件输入”。
标签: java intellij-idea filenotfoundexception