Kotlin – Copy Directory

Kotlin – Copy Directory

To copy a directory in Kotlin, you can use the copyRecursively() function of the File class from the java.io package. This function allows for recursively copying a directory, including all its files and subdirectories.

This tutorial demonstrates the use of copyRecursively() to copy a directory in Kotlin with an example.

Steps to Copy a Directory Using File.copyRecursively() in Kotlin

Here’s how to copy a directory recursively using File.copyRecursively():

  1. Import the File class from the java.io package.
  2. Specify the source and destination directory paths as File objects.
  3. Invoke the copyRecursively() method on the source File object, passing the destination File object as an argument.
  4. Optionally, handle any exceptions that might occur during the copying process, such as IOException.

Kotlin Example Program to Copy a Directory

In the following example, we’ll copy a directory named 'dir1' to a new location named 'dir2' using File.copyRecursively().

Main.kt

import java.io.File

fun main() {
    val sourceDir = File("dir1") // Replace with your source directory path
    val destDir = File("dir2") // Replace with your destination directory path

    try {
        val result = sourceDir.copyRecursively(destDir, overwrite = true)
        if (result) {
            println("Directory copied successfully.")
        } else {
            println("Directory not copied.")
        }
    } catch (e: Exception) {
        println("An error occurred while copying the directory: ${e.message}")
    }
}

Output

Directory copied successfully.

The output will indicate whether the directory was successfully copied. The overwrite = true argument allows existing files in the destination directory to be overwritten.

Summary

In this tutorial, we explored how to copy a directory in Kotlin using the File.copyRecursively() method.