簡體   English   中英

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

[英]Where does getResourceAsStream(file) search for the file?

我對getResourceAsStream()感到困惑;

我的包結構如下:

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

我想從floodlightdefault.properties中讀取。 這是我的代碼,位於net.floodlightcontroller包中:

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

但它失敗了,得到的is == null 所以我想知道getResourceAsStream(file)究竟是如何搜索file 我的意思是它通過某些PATH或按特定順序工作嗎?

如果是這樣,如何配置getResourceAsStream()查找的位置?

謝謝!

當您調用this.getClass().getClassLoader().getResourceAsStream(File) ,Java會在與this指示的類相同的目錄中查找該文件。 因此,如果您的文件結構是:

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

然后你會打電話給:

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

更好的是,將包結構更改為:

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

並致電:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM