Read and write values to properties file in Kotlin
A properties file consists of a set of key-value pairs. This article covers different ways to read or write values to the properties file in Kotlin.
1. Write values to properties file
The preferred way to write values to a properties file is to load it first from the classpath or file system into a Properties object and set the given property using its setProperty() function. Then write the properties to the properties file by passing a FileOutputStream to the store() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.OutputStream import java.util.* fun main() { val file = File("/var/www/html/config.properties") val prop = Properties() FileInputStream(file).use { prop.load(it) prop.setProperty("myKey", "myValue") val out: OutputStream = FileOutputStream(file) prop.store(out, "some comment") } // Print all properties prop.stringPropertyNames() .associateWith {prop.getProperty(it)} .forEach { println(it) } } |
2. Read values from properties file
The stringPropertyNames() function returns collection of keys present in the Properties object. The following example loads the current system properties into a Properties object using the System.getProperties() and then list out all system properties using the stringPropertyNames() function.
|
1 2 3 4 5 6 7 8 |
fun main() { val prop = System.getProperties() // Print all properties prop.stringPropertyNames() .associateWith {prop.getProperty(it)} .forEach { println(it) } } |
Here’s how you can load properties from the property file present on the file system.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.io.File import java.io.FileInputStream import java.util.* fun main() { val file = File("/var/www/html/config.properties") val prop = Properties() FileInputStream(file).use { prop.load(it) } // Print all properties prop.stringPropertyNames() .associateWith {prop.getProperty(it)} .forEach { println(it) } } |
That’s all about reading and writing values to the properties file in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)