Skip to main content

How to read and write properties files in Kotlin

How to read and write properties files in Kotlin.

Here's a step-by-step tutorial on how to read and write properties files in Kotlin:

  1. Import the necessary packages:

    import java.io.FileInputStream
    import java.io.FileOutputStream
    import java.util.Properties
  2. Reading Properties file:

    a. Create an instance of the Properties class:

    val properties = Properties()

    b. Load the properties from the file:

    val fileInputStream = FileInputStream("path/to/properties/file.properties")
    properties.load(fileInputStream)

    c. Access the properties using their keys:

    val value = properties.getProperty("key")
  3. Writing Properties file:

    a. Create an instance of the Properties class:

    val properties = Properties()

    b. Set the properties and their values:

    properties.setProperty("key1", "value1")
    properties.setProperty("key2", "value2")

    c. Save the properties to a file:

    val fileOutputStream = FileOutputStream("path/to/properties/file.properties")
    properties.store(fileOutputStream, "Optional comment")
  4. Reading and Writing Properties file using Kotlin DSL:

    a. Create a Kotlin properties file (.kts) with the desired properties:

    val properties = Properties().apply {
    setProperty("key1", "value1")
    setProperty("key2", "value2")
    }

    b. Load the properties from the file:

    val fileInputStream = FileInputStream("path/to/properties/file.kts")
    properties.load(fileInputStream)

    c. Access the properties using their keys:

    val value = properties.getProperty("key")

    d. Save the properties to a file:

    val fileOutputStream = FileOutputStream("path/to/properties/file.kts")
    properties.store(fileOutputStream, "Optional comment")
  5. Closing the streams:

    Don't forget to close the input and output streams after reading or writing the properties file. You can use the use function for automatic closing:

    fileInputStream.use {
    // read or write operations
    }
    fileOutputStream.use {
    // read or write operations
    }

That's it! You now know how to read and write properties files in Kotlin.