In this tutorial, you shall learn how to rename a directory in Kotlin identified by a given path, using File.renameTo() function, with example programs.

Kotlin – Rename a Directory

To rename a directory in Kotlin, you can use renameTo() function of java.io.File class.

Steps to rename a directory

  1. Consider that we have a directory (source) given by a path, and have to rename this directory to a new name (target).
  2. Create two file objects: one for the source directory, and one for the target directory (the new name to which we would like to rename to), with respective paths.
  3. Call renameTo() function on the source directory and pass the target directory as argument. The function returns true if renaming the directory is successful, else it returns false.
val sourceDir = File("path/to/source")
val targetDir = File("path/to/target")
sourceDir.renameTo(targetDir)
ADVERTISEMENT

Example

Consider that we have a directory part1 at mydata/set1/, and we would like to rename it to part1_foo.

Kotlin - Rename a Directory

In the following program, we shall rename the directory mydata/set1/part1 to mydata/set1/part1_foo by using File.renameTo() function.

Main.kt

import java.io.File

fun main() {
    val sourceDir = File("mydata/set1/part1")
    val targetDir = File("mydata/set1/part1_foo")
    if ( sourceDir.renameTo(targetDir) ) {
        println("Directory renamed successfully.")
    } else {
        println("Could not rename directory.")
    }
}

Output

Directory renamed successfully.
Kotlin - Rename a Directory

Reference tutorials for the above program

Conclusion

In this Kotlin Tutorial, we learned how to rename a directory using java.io.File.renameTo() function.