JAVA - 更新 .properties 文件

JAVA - Update .properties file

我正在尝试更新 jar 中的 .properties 文件,但没有成功。 在尝试了上千种不同的方法之后,我在这里得到了这个例子:

    final AbstractFileConfiguration prop = new PropertiesConfiguration("application.properties");

    System.out.println(prop.getProperty(property));

    if (prop.containsKey(property)) {
        prop.setProperty(property, value);
        prop.save();
    }

这为我返回了一个异常:

org.apache.commons.configuration.ConfigurationException: Could not save to URL jar:file:/home/pedepano/myjarapp.jar!/application.properties
at org.apache.commons.configuration.AbstractFileConfiguration.save(AbstractFileConfiguration.java:464)
at org.apache.commons.configuration.AbstractFileConfiguration.save(AbstractFileConfiguration.java:377)
at com.library.core.Configs.updateSimpleProperty(Configs.java:151)
at com.print.model.business.caixa.cnab240.listmodel.AbstractCnab240ListModel.mouseClicked(AbstractCnab240ListModel.java:111)
at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)
at java.awt.Component.processMouseEvent(Component.java:6528)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)

有人说无法在运行时更新 .properties 文件,有人说可以。我真的浪费太多时间试图找到答案...... 那可能吗? 如果是,如何? 如果没有,我可以做什么?

非常感谢!

您正试图写回已编译到您的 .jar 中的 .properties 文件,据我所知,这是不可能的;但是,您可以将该属性文件写入外部源。

File f = new File("my.properties");
OutputStream out = new FileOutputStream( f );
props.store(f, "a comment");

这将在您的 .jar 文件旁边创建该文件。

如果这是您选择的路线,您可能想先尝试从外部文件加载,如果找不到外部文件,则默认为内部文件。

     Properties properties = new Properties();
     try {      
             String propertiesFilePath = ("your file path");
             FileInputStream fis = new FileInputStream(propertiesFilePath);
             properties.load(fis);

             properties.setProperty("key","value");

             FileOutputStream fos = new FileOutputStream(propertiesFilePath);
             properties.store(fos,null);
             System.out.println("SUCCESS");
     }
     catch(Exception e) {
             System.out.println("FAILED");
     }