简体   繁体   English

从战争中加载配置文件

[英]Load config file from a war

I have a Maven project that I'm trying to package as both a war and a jar. 我有一个Maven项目,我试图将其打包为战争和罐子。 As part of my application / servlet initialisation (depending on whether I'm running the jar or the war), I need to read a file called server.ini . 作为我的应用程序/ servlet初始化的一部分(取决于我是运行jar还是战争),我需要读取一个名为server.ini的文件。 I've put the file in src/main/resources/server.ini and am trying to load it like so: 我把文件放在src/main/resources/server.ini并尝试加载它,如下所示:

System.class.getResourceAsStream("server.ini");

However, this always results in null . 但是,这总是会导致null What am I doing wrong? 我究竟做错了什么?

The server.ini file should be in the root of a resources directory. server.ini文件应位于资源目​​录的根目录中。

By placing it in the webapp you're making the file available via http , but you need it accessible on the classpath , which means that you should place it in the resources directory. 通过将它放在webapp您可以通过http使文件可用,但是您需要在classpath上访问它,这意味着您应该将它放在资源目录中。

There's a good chance web.xml or context.xml is better suited to what you're trying to do, but... web.xmlcontext.xml很有可能更适合你想要做的事情,但......

Try putting server.ini in WEB-INF/classes , or do something like this . 尝试把server.iniWEB-INF/classes ,或做一些像这样

The issue was that I was using the System classloader with an unqualified path, so it was expecting to find my server.ini in the java.lang package. 问题是我使用的是具有非限定路径的System类加载器,所以它期望在java.lang包中找到我的server.ini

Since my file is in src/main/resources , I should just use the classloader of my current class, with an absolute path: 由于我的文件在src/main/resources ,我应该使用当前类的类加载器,使用绝对路径:

getClass().getResourceAsStream("/server.ini")

This works in both the war and the jar. 这适用于战争和罐子。

The " Preferred way of loading resources in Java " question has a great explanation of resource loading. 在Java中加载资源的首选方式 ”问题对资源加载有很好的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM