使用 maven 构建后未找到来自 src/main/resources 的资源 [英] Resource from src/main/resources not found after building with maven

查看:44
本文介绍了使用 maven 构建后未找到来自 src/main/resources 的资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我在我的 java 应用程序中使用来自 src/main/resources 的配置文件.我在课堂上是这样读的:

Hello I'm using a configuration file from src/main/resources in my java application. I'm reading it in my Class like this :

new BufferedReader(new FileReader(new File("src/main/resources/config.txt")));

所以现在我使用 mvn assembly:assembly 用 maven 构建它.这是我的 pom.xml 中的一点:

So now I'm building this with maven using mvn assembly:assembly. Here is the bit for that in my pom.xml :

<plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <finalName>TestSuite</finalName>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>com.some.package.Test</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>

所以当我运行我的应用程序时,我收到了这个错误:

So when I run my app I get this error :

srcmain
esourcesconfig.txt (The system cannot find the path specified)

但是当我右键单击我组装的罐子时,我可以看到它的内部,有人知道我做错了什么吗?

But when I right click on my assembled jar I can see it inside, anyone knows what I'm doing wrong?

推荐答案

src/main/resources 中的资源会放到类路径的根目录下,所以你需要获取资源如:

Resources from src/main/resources will be put onto the root of the classpath, so you'll need to get the resource as:

new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/config.txt")));

您可以通过查看 maven 生成的 JAR/WAR 文件进行验证,因为您会在存档的根目录中找到 config.txt.

You can verify by looking at the JAR/WAR file produced by maven as you'll find config.txt in the root of your archive.

这篇关于使用 maven 构建后未找到来自 src/main/resources 的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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