[英]Reading Properties file every time in the execution in Java
I have to read properties file "MyProperty.properties" from "ReadProp.java" class given my the following directory structure of my "war" file I am going to deploy. 给定我要部署的“ war”文件的以下目录结构,我必须从“ ReadProp.java”类中读取属性文件“ MyProperty.properties”。
MyApp.war
| ----MyProps
| |--MyProperty.properties
|---WEB-INF |
|--classes
|---ReadProp.java
I am going to deploy this "war" file in "Sun portal server". 我将在“ Sun门户服务器”中部署此“ war”文件。 But I should not change any of this directory structure because of the requirement specification.
但是由于需求规范,我不应该更改任何此目录结构。
I am reading this file in the following way 我正在通过以下方式读取此文件
String path = servletContext.getRealPath("/MyProps/MyProperty.properties"); System.out.println("path: " + path);
Properties prop = new Properties();
try {
prop.load(new FileInputStream(path));
);
} catch (Exception e) {
e.printStackTrace();
}
String name= prop.getProperty("name");
It is working fine. 一切正常。 but the problem is if I change properties file after loading the application the changes are not reflecting.
但是问题是,如果在加载应用程序后更改属性文件,更改不会反映出来。
I may change the properties file anytime how to do If I want that changes should be reflected . 我可以随时更改属性文件的操作方法如果我希望更改应反映出来。 I mean the application should load the properties file everytime in the exexcutio
我的意思是应用程序应该每次在exexecutio中加载属性文件
You won't see changes unless you bounce the app server. 除非您启动应用服务器,否则您将看不到任何更改。
A better choice would be to put the .properties file in your /WEB-INF/classes folder and read it from the CLASSPATH using getResourceAsStream()
. 更好的选择是将.properties文件放在/ WEB-INF / classes文件夹中,并使用
getResourceAsStream()
从CLASSPATH中读取它。
You don't say where you're reading the code. 您没有说要在哪里阅读代码。 You might have to implement a
Timer
task to periodically wake up and reload the .properties file. 您可能必须实现
Timer
任务才能定期唤醒并重新加载.properties文件。
You might also try a WatchService
if you're using JDK 7: 如果您使用的是JDK 7,也可以尝试使用
WatchService
:
您需要为该示例链接使用java 7 WatchService
I got the answer: 我得到了答案:
String path = servletContext.getRealPath("/MyProps/MyProperty.properties");
System.out.println("path: " + path);
Properties prop = new Properties();
try {
File f = new File(path);
FileInputStream fis = new FileInputStream(f);
prop.load(fis);
}
catch (Exception e) {
e.printStackTrace();
}
The newer way to do this is: 更新的方法是:
Path path;
try {
path = Paths.get("MyProperty.properties");
if (Files.exists(path)) {
props = new Properties();
props.load(Files.newInputStream(path));
}
} catch (IOException e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.