How to write values in a properties file through java code

前端 未结 4 1909
庸人自扰
庸人自扰 2020-11-30 09:30

I have an issue.

I have a properties file. I want to store some values in that file and will implement in the code whenever it is required. Is there any way to do t

4条回答
  •  [愿得一人]
    2020-11-30 10:10

    Load the properties file using java.util.Properties.

    Code snippet -

    Properties prop = new Properties();
    InputStream in = getClass().getResourceAsStream("xyz.properties");
    prop.load(in);
    

    It provides Properties#setProperty(java.lang.String, java.lang.String) which helps to add new property.

    Code snippet -

    prop.setProperty("newkey", "newvalue");
    

    This new set you can save using Properties#store(java.io.OutputStream, java.lang.String)

    Code Snippet -

    prop.store(new FileOutputStream("xyz.properties"), null);
    

提交回复
热议问题