【问题标题】:Java.io.FileNotFoundException using File objectJava.io.FileNotFoundException 使用 File 对象
【发布时间】:2013-02-04 15:26:34
【问题描述】:
File read = new File("Numbers.txt");
Scanner inputFile = new Scanner(read);

while(inputFile.hasNext())
{
    sum = inputFile.nextDouble() + sum;
    count++;
}

inputFile.close();//close the input file

我正在尝试从文本文件Numbers.txt 中读取数据,并且以下代码可以正常编译,但在程序运行时出现Java.io.FileNotFoundException 错误。我也试过输入完整的文件路径,但我可能做错了。有什么想法吗?

【问题讨论】:

  • 如果文件确实存在,这应该可以正常工作。可能文件名不正确。
  • 您使用的是相对路径,该路径将相对于正在运行的 Java 程序的工作目录进行解析。在 Java 中处理文件时,最好指定绝对路径。

标签: java filenotfoundexception java-io


【解决方案1】:

确保您的文本文件位于您的 java 文件所在的文件夹中 因为您使用了直接路径。 如果仍然无法正常工作,请尝试此代码检查。

BufferedReader read = new BufferedReader(new FileReader("yourTextFile.txt"));
String line = read.readLine();

while(line !=null)
{
     System.out.println(line);
     line=read.readLine();
}
}catch(Exception ex)
{System.out.println(ex.getMessage());}

【讨论】:

  • 哇,谢谢。这是唯一一个不在文件夹中的文件。程序现在有效。非常感谢。
【解决方案2】:

尝试添加

System.out.println("Full path is " + read.getCanonicalPath()
                   + ", canRead=" + read.canRead()
                   + ", exists=" + read.exists());

然后看看你的文件系统上是否存在完整路径,根据canRead是否可读。

如果文件是符号链接,canRead 可能会返回 true,因为即使链接指向的文件不可读,符号链接也是可解析的。要正确处理符号链接,您确实需要使用新的 java.nio.file API。

【讨论】:

  • 谢谢,这帮助我意识到上面的答案是错误的。
猜你喜欢
  • 2016-01-05
  • 1970-01-01
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 2014-03-17
  • 1970-01-01
相关资源
最近更新 更多