问题
I have a property files message_en.properties message_de.properties in my project and I have entry InfoBox_description=welcome to the this application and corresponding value in German. Now user should be allowed to change the description dynamically and same should reflect in other property file also with right conversion.how should I do this? I am using JSF2 and prime faces
Thanks in advance
回答1:
Assuming you have your properties file inside your war, in a package in the source folder, this is how you load it in the managed bean:
Properties properties = new Properties();
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
properties.load(classLoader.getResourceAsStream("/yourfile.properties"));
} catch (IOException e) {
// handle exception
}
// then initialize attributes with the contents of properties file. Example:
property1 = properties.getProperty("property1");
property2 = properties.getProperty("property2");
Then, when user updates values (submit forms) and you want to update the properties file, do the following:
properties.setProperty("property1", property1);
properties.setProperty("property2", property2);
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("/yourfile.properties");
properties.store(new FileOutputStream(new File(url.toURI())), null);
} catch (Exception e) {
// handle exception
}
If the properties file is not in the war (it's in the file system of the server) it is also possible but a little more complex..
EDIT: as BalusC explained, having the properties file that changes inside your war is not convenient because if you redeploy your war, then changes are lost. You could put the properties file in the file system of the server if you have access to it; or don't use properties files (use database instead)
来源:https://stackoverflow.com/questions/16828991/dynamically-editing-property-file