【发布时间】:2015-01-09 19:44:22
【问题描述】:
我在尝试读取文件时不断收到相同的错误。该文件确实存在于目录中,我做错了什么?
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MenuSample{
public static void main(String[] args) {
File f = new File("C:/Users/Joe/Documents/workspace/ArtificialLifeFX/res/latest.txt");
Scanner scanner = null;
try {
scanner = new Scanner(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scanner.useDelimiter("\r\n");
}
}
我收到以下错误:
java.io.FileNotFoundException: C:\Users\Joe\Documents\workspace\ArtificialLifeFX\res\latest.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at test.MenuSample.main(MenuSample.java:16)
Exception in thread "main" java.lang.NullPointerException
at test.MenuSample.main(MenuSample.java:21)
如果我太天真了,请原谅我,我是 Java 新手。我在 Windows 7 上运行 Eclipse Luna。
【问题讨论】:
-
一些想法...Java 对文件名区分大小写,而 Windows 则不区分大小写,因此请确保大小写匹配。
-
另外,字符串中的分隔符是正斜杠,windows 是反斜杠。我不确定 Java 是否足够聪明来解决这个问题。
-
在创建扫描仪之前检查 f.exists() 和 f.canRead() 的值不会有什么坏处。
-
您确定该文件在 Java 程序运行之前已经存在吗?或者您是否希望 Java 代码在文件不存在时自动创建文件(因为这不会发生)?您必须使用 File#createNewFile()。
-
您应该设置资源管理器以显示文件扩展名。 This is how you do that.
标签: java file filenotfoundexception fileinputstream