如何通过java代码在属性文件中写入值

我有一个问题。

我有一个属性文件。 我想在该文件中存储一些值,并在需要时在代码中实现。 有没有办法做到这一点?

我正在使用Properties类来做到这一点..

使用java.util.Properties加载属性文件。

代码段 –

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

它提供了Properties#setProperty(java.lang.String, java.lang.String) ,它有助于添加新属性。

代码段 –

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

您可以使用Properties#store(java.io.OutputStream, java.lang.String)保存这个新集

代码片段 –

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

您可以通过以下方式执行此操作:

  1. 首先使用object.setProperty(String obj1, String obj2)Properties对象中object.setProperty(String obj1, String obj2) Properties

  2. 然后通过将FileOutputStream传递给properties_object.store(FileOutputStream, String)将其写入您的File

这是示例代码:

 import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.Properties; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.File; class Main { static File file; static void saveProperties(Properties p) throws IOException { FileOutputStream fr = new FileOutputStream(file); p.store(fr, "Properties"); fr.close(); System.out.println("After saving properties: " + p); } static void loadProperties(Properties p)throws IOException { FileInputStream fi=new FileInputStream(file); p.load(fi); fi.close(); System.out.println("After Loading properties: " + p); } public static void main(String... args)throws IOException { file = new File("property.dat"); Properties table = new Properties(); table.setProperty("Shivam","Bane"); table.setProperty("CS","Maverick"); System.out.println("Properties has been set in HashTable: " + table); // saving the properties in file saveProperties(table); // changing the property table.setProperty("Shivam", "Swagger"); System.out.println("After the change in HashTable: " + table); // saving the properties in file saveProperties(table); // loading the saved properties loadProperties(table); } }