【发布时间】:2015-04-25 13:34:23
【问题描述】:
我正在尝试用 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;
}
这是堆栈跟踪:
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)
我不明白如果文件与程序位于完全相同的文件夹中,怎么找不到该文件。我在 Eclipse 中运行该程序,并检查了我的运行配置是否有任何杂散参数,但没有。有谁知道出了什么问题?
【问题讨论】:
-
可能的原因是,文件不在您认为的位置。您可以使用
System.out.println(new File(".").getAbsolutePath());之类的东西来测试它,它将输出当前工作目录,这是文件需要驻留的位置。
标签: java