[英]Java find the relative path of the configuration file in the war file
I am trying to access the config.properties file which was previously placed in the config folder.我正在尝试访问之前放置在 config 文件夹中的 config.properties 文件。 after some research, I moved it to the WEB-INF folder.
经过一番研究,我将其移至 WEB-INF 文件夹。 but even after I moved it, it still return java.lang.NullPointerException whenenver I run my my program.
但即使在我移动它之后,当我运行我的程序时,它仍然会返回 java.lang.NullPointerException。 code used to store some password information as below:
用于存储一些密码信息的代码如下:
ClassLoader resource = ConnectionManager.class.getClass().getClassLoader();
URL path = ConnectionManager.class.getClass().getResource("/WEB-INF/config.properties");
props.load(new FileInputStream(path.getFile()));
String passwordds = props.getProperty("datasource.password");
these are the codes that I found and I try to use it but still I got the null exception.这些是我找到的代码,我尝试使用它,但仍然出现 null 异常。
I cannot use absolute path due to this project will be deploy to production server as in.war file.我不能使用绝对路径,因为这个项目将作为 in.war 文件部署到生产服务器。 please advise what is the best way as I am still beginner.
请告知什么是最好的方法,因为我还是初学者。
You should check the war your build tool generated, and find where your config file really are.您应该检查您的构建工具生成的战争,并找到您的配置文件的真正位置。
For maven project, the default resource dir is /src/main/resources/对于 maven 项目,默认资源目录为 /src/main/resources/
So /src/main/resources/config.properties will be put at /WEB-INF/classes/config.properties in a war.所以 /src/main/resources/config.properties 将被放在 /WEB-INF/classes/config.properties 中。
You can use getClass().getResourceStream("/config.properties")
(getResource sometimes not work will in j2ee environment) to get it.您可以使用
getClass().getResourceStream("/config.properties")
(getResource 有时在 j2ee 环境中不起作用)来获取它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.