getResourceAsStream(file)在哪里搜索文件? [英] Where does getResourceAsStream(file) search for the file?

查看:81
本文介绍了getResourceAsStream(file)在哪里搜索文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 getResourceAsStream();

感到困惑我的包结构如下:

My package structure looks like:

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


b $ b

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

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

但它失败了,得到 is == null 。所以我想知道 getResourceAsStream(file)究竟是如何搜索文件。我的意思是它通过某些 PATH 或在某个订单中工作?

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?

如果是,如何配置 getResourceAsStream()的地方?

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

Thx!

推荐答案

,Java在与 this 指示的类相同的目录中查找该文件。因此,如果您的文件结构是:

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:

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

然后你需要调用:

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
    |__ ...

只需拨打电话:

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

这篇关于getResourceAsStream(file)在哪里搜索文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆