https://grokonez.com/java/java-read-write-properties-object-properties-file-properties-file
Java – Read/write Properties from/to .properties file
In the post, we show how to read/write Properties object from/to Properties File (.properties file).
I. Java - Write Properties object to Properties File
1. Properties store() method
We use java.util.Properties.store() methods:
// 1.
public void store(OutputStream out,
String comments)
throws IOException
-> Writes this property list (key and element pairs) in this Properties table
to the output stream in a format suitable for loading into a Properties table using the load(InputStream) method.
// 2.
public void store(Writer writer,
String comments)
throws IOException
-> Writes this property list (key and element pairs) in this Properties table
to the output character stream in a format suitable for using the load(Reader) method.
2. Program - write Properties to File
package com.javasampleapproach.propertiesfile;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Properties;
public class JavaWriteProperties2File {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("db.username", "username");
properties.put("db.password", "password");
properties.put("db.driver", "org.postgresql.Driver");
properties.put("db.url", "jdbc:postgresql://localhost/testdb");
/*
* Approach 1:
* use -> 'java.util.Properties.store(OutputStream out, String comments) throws IOException'
*/
String propertiesFile = System.getProperty("user.dir") + "\\file.properties";
try(OutputStream propertiesFileWriter = new FileOutputStream(propertiesFile)){
properties.store(propertiesFileWriter, "save to properties file");
}catch(IOException ioe){
ioe.printStackTrace();
}
/*
* Approach 2:
* use -> 'java.util.Properties.store(Writer writer, String comments) throws IOException'
*/
propertiesFile = System.getProperty("user.dir") + "\\file_1.properties";
try(Writer propertiesFileWriter = new FileWriter(propertiesFile)){
properties.store(propertiesFileWriter, "save to properties file");
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
-> .properties output file:
More at:
https://grokonez.com/java/java-read-write-properties-object-properties-file-properties-file
Java – Read/write Properties from/to .properties file
Latest comments (0)