Kotlin – Replace String in File

Kotlin – Replace String in File

To replace a string in a file in Kotlin, you can read the file, perform the replacement, and then write the modified content back to the file.

Steps to Replace String in File

Follow these steps to replace a specific string with a replacement string in a file given by a file path.

  1. Import java.io.File class.
  2. Given file path in filePath variable.
  3. Given search string in searchString, and replacement string in replacementString variables. We need to replace search string with replacement string in the given file.
  4. Create a File object using the file path filePath.
  5. Check if the file exists using the exists() method. If the file exists, then read the original content of the file using File.readText().
  6. Replace the search string with the replacement string using the String.replace() function on the original content.
  7. Writes the modified content back to the file using File.writeText().

Example Program to Replace String in File

In this example program, we shall replace the string "apple" with "cherry" in the file 'example.txt'.

The original contents of the 'example.txt' is given below.

Kotlin - Replace String in File - Input file
Original File content

Main.kt

import java.io.File

fun main() {
    val filePath = "example.txt" // Replace with the path to your file
    val searchString = "apple"
    val replacementString = "cherry"

    try {
        val file = File(filePath)

        if (!file.exists()) {
            println("File not found: $filePath")
            return
        }

        // Read the file
        val originalContent = file.readText()

        // Replace the string
        val modifiedContent = originalContent.replace(searchString, replacementString)

        // Write the modified content back to the file
        file.writeText(modifiedContent)

        println("String '$searchString' replaced with '$replacementString' in '$filePath'")
    } catch (e: Exception) {
        println("An error occurred: ${e.message}")
    }
}

Output

String 'apple' replaced with 'cherry' in 'example.txt'

example.txt after the execution of program

Kotlin - Replace String in File - After replacement
File content after string replacement in file

Summary

In this Kotlin File Operations tutorial, we have seen how to replace a string in file using File class and String.replace(), with a detailed step by step process, and example program.