How to change getResource to getResourceAsStream

2019-09-07 16:12发布

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

My code is

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();
}

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

标签: java file
1条回答
劳资没心,怎么记你
2楼-- · 2019-09-07 16:37

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.

So:

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

FileInputStream fis = new FileInputStream(fin);

ReadResourceFromStream(fis);

Changes to:

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

ReadResourceFromStream(is);
查看更多
登录 后发表回答