java - 动态编辑属性文件

标签 java jsf-2 primefaces

我的项目中有一个属性文件 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/

相关文章:

java - 调整位图大小

java - JAXB 解码未知 XML 内容的子集

java - 从 arraylist 中删除对象会留下 null

jsf-2 - 带有所需单选按钮的 PrimeFaces 数据表

javascript - p :dialog not showing in tabs on tabview

java - 将 Scala 编织到现有的 Java EE 项目中?

java - 三次贝塞尔曲线 : Maximum Gradient and Collision Avoidance?

file-upload - primefaces 显示数据库中的图像

javascript - 设置热键以在不使用 widgetVar 的情况下折叠面板

ajax - Primefaces:关闭对话框时咆哮消息立即消失