【发布时间】:2014-05-09 17:44:47
【问题描述】:
我从这段代码中得到一个文件未找到异常,即使它在 try catch 语句中并且我不确定出了什么问题,该文件在项目文件夹中并且被称为“someFile.txt”。这是主要方法:
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("no arguments given");
return;
}
double FRE = sortFile(args[0]);
System.out.println("Readability of file " + args[0] + "= " + FRE);
}
而这是发生异常的sortFile方法:
public static double sortFile(String FileName) {
int nWords = 0;
int nSyllables = 0;
int nSentences = 0;
File text = new File(FileName);
try {
Scanner sc = new Scanner(text);
while (sc.hasNext()) {
contents.add(sc.next());
++nWords;
}
sc.close();
for (String e : contents) {
getNumSyllables(e);
}
} catch (FileNotFoundException e) {
System.out.println("The file" + FileName + "could not be opened.");
e.printStackTrace();
}
double FRE = getFRE(nWords, nSyllables, nSentences);
return FRE;
}
感谢您的帮助:)
【问题讨论】:
-
能否请您显示项目层次结构,它比这段代码更有帮助。
-
只是一个建议。始终在 catch 语句之后的 finally 块中关闭您的流等。这样它就会100%肯定被关闭。您还尝试在 try 之上创建文件。放置文件文本=新文件(文件名);在尝试中。
-
说真的,即使它在 try 和 catch 块中,你也会得到一个 filenotfoundexception,但是在这之后没有代码打印一些东西并且你打印了 stackstrace,所以你无法知道异常是否被捕获或不是……
-
@kai 他可以调试/查看他的日志以查看是否捕获了异常。但问题可能是在您使用的位置找不到该文件。
-
如果你使用 Java 7 使用 java.nio.file;至少你会有的例外是有意义的
标签: java filenotfoundexception