我的项目中有一个属性文件 message_en.properties message_de.properties,并且我有条目 InfoBox_description=welcome to the this application 以及德语的相应值。现在应该允许用户动态更改描述,并且同样应该通过正确的转换反射(reflect)在其他属性文件中。我应该如何执行此操作?我正在使用 JSF2 和 prime faces
提前致谢
最佳答案
假设您的属性文件位于您的 war 中(位于源文件夹的包中),这就是将其加载到托管 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");
然后,当用户更新值(提交表单)并且您想要更新属性文件时,请执行以下操作:
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
}
如果属性文件不在 war 中(它在服务器的文件系统中),也是可能的,但稍微复杂一点..
编辑:正如 BalusC 所解释的那样,在 war 中更改属性文件并不方便,因为如果您重新部署 war ,那么更改就会丢失。如果您有权访问该属性文件,则可以将其放入服务器的文件系统中;或者不使用属性文件(改为使用数据库)
关于java - 动态编辑属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16828991/