Maven项目中的资源和配置加载 [英] Resources and config loading in maven project

查看:141
本文介绍了Maven项目中的资源和配置加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Maven进行桌面应用.我阅读了有关 Maven标准字体目录布局的信息我现在有这个项目结构:

I'm using Maven for desktop applycation. I read about Maven standart directory layout and I have this project structure for now:

App
|-- pom.xml
`-- src
    |-- main
        |-- java
        |   `-- java classes
        |-- resources
        |   `-- images
        |       `-- app images
        `--config
           `--config.xml

我想找到一种加载资源和配置文件的方法.我阅读了一些文章和主题,并找到了这个(从我的代码中得到的简化示例):

I want to find a way to load my resources and config files. I read some articles and topics and found this (simplified example from my code):

//class for loading config
public class Preferences {
    public Preferences() {
        InputStream image = Preferences.class.getResourceAsStream("images/image.png");
        InputStream config = Preferences.class.getResourceAsStream("config.xml");
    }        
}

但是image和config变量包含null.我正在尝试不同的加载方式(从根文件夹,使用this.getClass()而不是Preferences.class等),但是我总是空值.我真的不了解这个资源加载系统,也没有找到任何关于它的好的文档.如果有人对这种机制给出了很好的解释(或者只是在文档上提供了链接),那就太好了. 因此,主要问题是:如何加载资源和配置文件?

But image and config variables contains null. I was trying different variants of loading (from root folder, with this.getClass() instead of Preferences.class, and others), but I always have null. I really don't understand this resource loading system and I didn't find any good documentation about it. It would be nice, if somebody gives a good explanation about this mechanism (or just give a link on docs). So, the main question is: How can I load my resources and config files?

推荐答案

我想我找到了解决方案.正如Juned Ahsan和mR_fr0g所写,我需要使用ClassLoader类,而不是this.getClass().getResource().但是,它仅适用于资源文件夹.但是maven允许将其他文件夹添加为资源文件夹.我只需要将此部分添加到pom.xml:

I think I found the solution. As Juned Ahsan and mR_fr0g write, I need to use ClassLoader class, instead of this.getClass().getResource(). But, it works only for resource folder. But maven allows to add other folders as resource folders. I was just needed to add this section to pom.xml:

<build>
    <resources>
        <resource>
            <directory>src/main/config</directory>
        </resource>
    </resources>
</build>

有效的Java代码是:

And working java code is:

InputStream image = this.getClass().getClassLoader().getResourceAsStream("images/image.png");
InputStream config = ClassLoader.getSystemResourceAsStream("config.xml");

这篇关于Maven项目中的资源和配置加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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