【问题标题】:Fetching a resource in Java main method在 Java 主方法中获取资源
【发布时间】:2012-10-04 17:11:27
【问题描述】:

我试图通过调用MainClass.class.getResource("/Resources/file.extension") 并使用getPath() 将其传递给File 的构造函数来在我的Java 应用程序中打开一个资源。接下来,当我用File 初始化一个新的FileInputStream 时,我得到一个FileNotFoundException。完整的堆栈跟踪如下所示。

java.io.FileNotFoundException: E:\user\Documents\NetBeansProjects\Project name\build\classes\Resources\file.csv (The system cannot find the path specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at my.secret.project.MainClass.main(MainClass.java:27)

这是我的代码。

File file = new File(MainClass.class.getResource("/Resources/file.extension").getPath());

...

InputStream in = new FileInputStream(file);

【问题讨论】:

  • 文件是否存在于指定位置?
  • 我会使用MainClass.class.getResourceAsInputStream(path)

标签: java resources filenotfoundexception


【解决方案1】:

您的整个代码可以替换为简单的:

InputStream in = MainClass.class.getResourceAsStream("/Resources/file.extension");

无需使用File。事实上,您的 CLASSPATH 上的文件可能指向 JAR/WAR 中的某个位置,这肯定是行不通的。前往Class.getResourceAsStream() 获取战利品以了解详情。

【讨论】:

  • 很好,谢谢!等待几分钟,我会接受它作为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多