Java getResourceAsStream(file) 在哪里搜索文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19570608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:25:23  来源:igfitidea点击:

Where does getResourceAsStream(file) search for the file?

javaclassjvm

提问by qweruiop

I've got confused by getResourceAsStream();

我被搞糊涂了getResourceAsStream()

My package structure looks like:

我的包结构如下所示:

\src
|__ net.floodlightcontroller // invoked getResourceAsStream() here
|__ ...
|__ resources
    |__ floodlightdefault.properties //target
    |__ ...

And I want to read from floodlightdefault.properties. Here is my code, lying in the net.floodlightcontrollerpackage:

我想从 Floodlightdefault.properties 中读取。这是我的代码,位于net.floodlightcontroller包中:

package net.floodlightcontroller.core.module;
// ...
InputStream is = this.getClass().getClassLoader()
                 .getResourceAsStream("floodlightdefault.properties");

But it failed, getting is == null. So I'm wondering how exactly does getResourceAsStream(file)search for the file. I mean does it work through certain PATHs or in a certain order?

但它失败了,得到is == null. 所以我想知道如何getResourceAsStream(file)搜索file. 我的意思是它是通过某些PATHs 还是按特定顺序工作

If so, how to config the places that getResourceAsStream()looks for?

如果是这样,如何配置getResourceAsStream()寻找的地方?

Thx!

谢谢!

采纳答案by Nathaniel Jones

When you call this.getClass().getClassLoader().getResourceAsStream(File), Java looks for the file in the same directory as the class indicated by this. So if your file structure is:

当您调用 时this.getClass().getClassLoader().getResourceAsStream(File),Java 在与 指示的类相同的目录中查找文件this。所以如果你的文件结构是:

\src
|__ net.floodlightcontroller.core.module
    |__ Foo.java
|__ ...
|__ resources
    |__ floodlightdefault.properties //target
    |__ ...

Then you'll want to call:

然后你会想打电话:

InputStream is = Foo.class.getClassLoader()
             .getResourceAsStream("..\..\..\resources\floodlightdefault.properties");

Better yet, change your package structure to look like:

更好的是,将您的包结构更改为:

\src
|__ net.floodlightcontroller.core.module
    |__ Foo.java
    |__ floodlightdefault.properties //target
    |__ ...

And just call:

只需调用:

InputStream is = Foo.class.getClassLoader()
             .getResourceAsStream("floodlightdefault.properties");