如何访问maven项目中的XML文件,以便在打包时保持可用 [英] How to access a XML file in a maven project so it stays available when packaged

查看:237
本文介绍了如何访问maven项目中的XML文件,以便在打包时保持可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个maven web-app项目,需要使用jetty启动:在eclipse中进行开发/调试的运行爆炸目标。

I currently started working on a maven web-app project that needs to be launched with the jetty:run-exploded goal for development/debugging in eclipse.

现在,我有一个XML文件,我需要在运行时访问这些内容。我的问题是:在哪里放置文件,以便执行读取的代码在爆炸和打包(即在WAR)模式下工作?

Now, I have an XML file which contents I need to access at runtime. My problem is: where to put the file so that the code that does the reading works both in "exploded" and packaged (i.e. in the WAR) mode?

放置src / main / java中的文件(以便在类路径中)不会删除它,因为maven过滤掉包装上的所有非java文件。
当文件在src / main / resources中时,一个意思是找出项目的根路径(在eclipse开发期间)并查看该目录 - 但是当这个目录不再是这种情况时项目将被打包。

Putting the file in src/main/java (so as to be in the classpath) won't cut it since maven filters out all non-java files on packaging. When the file is in src/main/resources, one mean would be to figure out the root path of the project (during eclipse development) and look into that directory - but this won't be the case anymore when the project will be packaged.

当然,我可以编写试图从两个位置读取文件的代码,但这看起来相当麻烦。有什么建议?

Of course I could go into writing code that tries to read the file from both locations, but this seems rather cumbersome. Any suggestions?

推荐答案

复制 src / main / resources 中的文件到目标/类目录,并在类路径上可用。只需从类路径中读取它们即可。如如何向我的JAR添加资源?中所述maven文档(这里有一个测试资源):

Files in src/main/resources are copied to the target/classes directory and are available on the class path. Just read them from the class path. As explained in How do I add resources to my JAR? from the maven documentation (with a test resource here):


在单元测试中,你可以使用一个简单的
代码片段,如以下
访问
测试所需的资源:

In a unit test you could use a simple snippet of code like the following to access the resource required for testing:

...

// Retrieve resource
InputStream is = getClass().getResourceAsStream("/test.properties" );

// Do something with the resource

...


这篇关于如何访问maven项目中的XML文件,以便在打包时保持可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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