getResourceAsStream不适用于每个类? [英] getResourceAsStream not working for every class?
问题描述
我有一个使用一些txt文件的jar文件。为了得到它们,它使用 Class.getResourceAsStream
函数。
I have a jar file that uses some txt files. In order to get them it uses Class.getResourceAsStream
function.
Class A
{
public InputStream getInputStream(String path) throws Exception {
try {
return new FileInputStream(path);
} catch (FileNotFoundException ex) {
InputStream inputStream = getClass().getResourceAsStream(path);
if (inputStream == null)
throw new Exception("Failed to get input stream for file " + path);
return inputStream;
}
}
}
此代码运行正常。
问题是,如果我将类A定义为 extends java.io.File
,那么我从 getResourceAsStream
为空。
Problem is, if I define class A as extends java.io.File
, the InputStream I get from getResourceAsStream
is null.
另外,如果我将A类作为常规类(未继承),并定义B类as:
Also, if I leave class A as regular class (not inherited), and define class B as:
Class B extends java.io.File
{
public InputStream getInputStream(String path) throws Exception
{
return new A().getInputStream(path);
}
}
返回的InputStream仍为空。
the returned InputStream is still null.
有什么问题?有没有办法从继承文件
的类中访问该文件?
What is the problem? Is there a way to access the file from the class that inherits File
?
谢谢,
推荐答案
我怀疑这与包相关而不是继承。
I suspect this is more to do with packages than inheritance.
如果你的班级在一个包中,然后 getResourceAsStream()
将相对于该包,除非你用/启动它(这使它成为绝对资源)。另一种方法是使用 getClass()。getClassLoader()。getResourceAsStream()
,它不知道路径是否相对于包。
If your class is in a package, then getResourceAsStream()
will be relative to that package unless you start it with "/" (which makes it an "absolute" resource). An alternative is to use getClass().getClassLoader().getResourceAsStream()
which doesn't have any idea of a path being relative to a package.
只是继承文件
不应该影响行为。如果您真的相信它,请发布一个简短但完整的程序来证明问题。
Just subclassing File
shouldn't affect the behaviour at all. If you really believe it does, please post a short but complete program to demonstrate the problem.
这篇关于getResourceAsStream不适用于每个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!