我正在尝试用 Java 读取文件。我编写了一个程序并将文件保存在与我的程序完全相同的文件夹中。然而,我不断收到 FileNotFoundException。这是代码:
public static void main(String[] args) throws IOException {
Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
File f = new File("file.txt");
ArrayList<String> al = readFile(f, ht);
}
public static ArrayList<String> readFile(File f, Hashtable<String, Integer> ht) throws IOException{
ArrayList<String> al = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
int ctr = 0;
}
...
return al;
}
Run Code Online (Sandbox Code Playgroud)
这是堆栈跟踪:
Exception in thread "main" java.io.FileNotFoundException: file.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at csfhomework3.ScramAssembler.readFile(ScramAssembler.java:26)
at csfhomework3.ScramAssembler.main(ScramAssembler.java:17)
Run Code Online (Sandbox Code Playgroud)
如果文件与程序位于完全相同的文件夹中,我不明白如何找不到该文件。我在 eclipse 中运行程序,我检查了我的运行配置是否有任何杂散参数,但没有。有没有人看到有什么问题?
因为这File不是你认为的地方。打印您的程序试图读取的路径。
File f = new File("file.txt");
try {
System.out.println(f.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
根据File.getCanonicalPath()javadoc,规范路径名既是绝对的又是唯一的。规范形式的精确定义取决于系统。