https://grokonez.com/kotlin/kotlin-properties-read-write-properties-file-properties-xml-file

Kotlin Properties – Read/Write Properties from/to .properties/.XML File

In the post, we show how to Read/Write Properties from/to .Properties/.XML files by Kotlin language.

I. Kotlin - Read/Write Properties from/to .Properties file

1. Write Properties to .Properties file

1.1 Properties store() method

We use java.util.Properties.store() methods:

// 1.
fun store(out: OutputStream, comments: String): Unit

-> 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.
fun store(writer: Writer, comments: String): Unit

-> 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.

1.2 Kotlin Program – write Properties to .properties file


package com.javasampleapproach.kotlin.properties

import java.io.FileOutputStream
import java.io.FileWriter
import java.io.IOException
import java.util.Properties

fun main(args: Array) {
val properties = 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")

var propertiesFile = System.getProperty("user.dir") + "\\file.properties"
	
/*
 * 	Approach 1: 
 * 	use -> 'java.util.Properties.store(out: OutputStream, comments: String)'
 */
var fileOutputStream = FileOutputStream(propertiesFile)
properties.store(fileOutputStream, "save to properties file")

/*
 * 	Approach 2: 
 * 	use -> 'java.util.Properties.store(writer: Writer, comments: String)'
 */
propertiesFile = System.getProperty("user.dir") + "\\file_1.properties"
val fileWriter = FileWriter(propertiesFile)
properties.store(fileWriter, "save to properties file")

}

-> .properties output file:

More at:

https://grokonez.com/kotlin/kotlin-properties-read-write-properties-file-properties-xml-file

Kotlin Properties – Read/Write Properties from/to .properties/.XML File

#kotlin #xml #properties

Kotlin Properties - Read/Write Properties from/to .properties/.XML File » grokonez
3.15 GEEK