In this tutorial, you shall learn how to replace all the occurrences of a specific string in a file in Kotlin, with example programs.

Kotlin – Replace string in a file

To replace a specific string in a file in Kotlin, you can read the file content to a string, then replace all the occurrences of specified search string with a replacement string, and write the resulting content back to the file.

Steps to replace string in a file

  1. Consider that we have a text file identified by a given path. We have to replace all the occurrences of oldString with newString in this text file.
  2. Create a file object with the given path using java.io.File class.
  3. Read content from the file object using File.readText() function
  4. Replace the old string oldString with newString using String.replace() function
  5. Write the resulting string back to file using File.writeText() function.
</>
Copy
val file = File("path/to/text/file")
val content = file.readText()
val updatedContent = content.replace(oldString, newString)
file.writeText(updatedContent)

Example

For this example, we will consider a file named info.txt.

Kotlin - Replace string in a file - Contents of file before replacement

In the following program, we will replace the search string "apple" with the replacement string "mango", in the file info.txt.

Main.kt

</>
Copy
import java.io.File

fun main() {
    val filePath = "info.txt"
    val oldString = "apple"
    val newString = "mango"

    val file = File(filePath)
    val content = file.readText()
    val updatedContent = content.replace(oldString, newString)

    println("$oldString replaced with $newString in $filePath")
    file.writeText(updatedContent)
}

Output

apple replaced with mango in info.txt
Kotlin - Replace string in a file - Contents of file after replacement

Reference tutorials for the above program

Conclusion

In this Kotlin Tutorial, we learned how to replace specific search string in a file by a replacement string.