gpt4 book ai didi

java - Netbeans 中的 FileNotFoundException

转载 作者:搜寻专家 更新时间:2023-11-01 01:56:42 25 4
gpt4 key购买 nike

我在 Netbeans 中有一个 java 应用程序项目。我只有一节课。我试着这样做

FileReader fr = new FileReader("sal.html");

我在同一个包下有文件 sal.html。但是当我运行时出现这个错误:

Errorjava.io.FileNotFoundException: sal.html (The system cannot find the file specified)

最佳答案

我的猜测是 Netbeans 正在从您的项目的根文件夹调用 JVM。引用 File Javadoc 的一部分:

By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

要验证相对路径解析,您可以尝试:

System.out.println(System.getProperty("user.dir"));
System.out.println(new File("sal.html").getAbsolutePath());

然后您可以将您的文件移动到 java 寻找它的任何地方。很可能是您的项目的根文件夹

您还可以考虑使用类加载器通过 getClass().getResourceAsStream("sal.html"); 读取文件作为包内的资源。这是访问资源的首选方式,因为您不再需要担心绝对路径与相对路径。如果资源在您的类路径中,您就可以访问它。参见 this answer更多。

关于java - Netbeans 中的 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7291282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com