简体   繁体   English

如何在一个.properties文件的末尾添加属性

[英]How to add property at the end in one .properties file

I am using the below code to write a property in a .properties file. 我正在使用下面的代码在.properties文件中写入属性。

InputStream inputStream = null;
    try {
        inputStream = file.getContents();
        Properties properties = new Properties();
        properties.load(inputStream);
        inputStream.close();
        properties.setProperty(propertyKey.trim(), propertyValue.trim());
        File file1 = file.getRawLocation().makeAbsolute().toFile();
        FileOutputStream outputStream = new FileOutputStream(file1);
        properties.store(outputStream, null);
        outputStream.close();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (CoreException ex) {
        ex.printStackTrace();
    }

Though it is adding the property in a sorted position but not at the end .But I want it will always be added at the end .How can I get that ? 虽然它是在排序后的位置添加属性,但不是在末尾添加。但是我希望它总是at the end添加。我怎么能得到它?

If you check the Properties file java doc, you can find the its using HashTable to store key value pair, the order of the key is nor guaranteed. 如果检查属性文件java doc,则可以使用HashTable查找其存储键值对,也不保证键的顺序。 Hence you need to use File Operations once its done you need to reload the properties file. 因此,一旦完成操作,您需要使用文件操作,您需要重新加载属性文件。

Use FileWriter to append to the end of file (second parameter of constructor defines appended mode): 使用FileWriter附加到文件末尾(构造函数的第二个参数定义附加模式):

try (FileWriter out = new FileWriter(file, true)) {
    out.append(property + "=" + value);
}
FileOutputStream outputStream = new FileOutputStream(file1,true);

The true tells it to append the new content to the end of the file. true表示将新内容附加到文件末尾。

Read more here 在这里阅读更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM