本文介绍了如何将getResource更改为getResourceAsStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序与getResource一起运行良好,但是将其放入jar文件后,其具有FileNotFoundException.它找不到test.conf.

The program runs well with getResource, but after made it into the jar file, it has FileNotFoundException. It cannot find out test.conf.

我的代码是

URL url = getClass().getResource("test.conf");
File fin = new File(url.getPath());

FileInputStream fis = null;
try {
    fis = new FileInputStream(fin);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

我认为我可以使用getResourceAsStream解决此问题.但是我不确定如何将getResource更改为getResourceAsStream.

I think I can fix the problem by using getResourceAsStream. But I'm not sure how to change getResource to getResourceAsStream.

推荐答案

您的示例表明您的阅读代码已在FileInputStream上运行.您应该能够使其与更通用的InputStream一起使用.这样一来,您就可以将getResourceStream()的结果传递给您的阅读代码,而不必担心文件.

Your example suggests that your reading code already works on a FileInputStream. You should be able to make it work with the more general InputStream. This will allow you to just pass the result of getResourceStream() to your reading code, without having to worry about Files.

所以:

URL url = getClass().getResource("test.conf");
File fin = new File(url.getPath());

FileInputStream fis = new FileInputStream(fin);

ReadResourceFromStream(fis);

更改为:

InputStream is = getClass().getResourceAsStream("test.conf");

ReadResourceFromStream(is);

这篇关于如何将getResource更改为getResourceAsStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-01 12:24