Kotlin – Copy File

Kotlin – Copy File

To copy a file in Kotlin, you can use Files.copy() method of java.nio.file package. Get the file Path objects for given source and destination file paths, and then use Files.copy() method with the file path Objects.

In this tutorial, we will go through a step by step guide on how to copy a source file to a destination, with an example.

Steps to copy File in Kotlin

Follow these steps to copy a File from sourceFilePath to destinationFilePath.

  1. Import the necessary classes: Files, Path, and StandardCopyOption from the java.nio.file package.
  2. Given source file path and destination file path.
  3. Create Path objects for the source and destination files.
  4. Use the Files.copy method to copy the source file to the destination file. The StandardCopyOption.REPLACE_EXISTING option is used to replace the destination file if it already exists.
  5. Include proper error handling using a try-catch block.

Kotlin Example Program to Copy File

In this example, we shall copy the source file 'example.txt' to a destination file 'example_copy.txt' using java.nio.file.Files.copy() method.

Kotlin - Copy File 'example.txt'


import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption

fun main() {
    val sourceFilePath = "example.txt" // Replace with the path to your source file
    val destinationFilePath = "example_copy.txt" // Replace with the path to your destination file

    try {
        // Create File Path objects for source and destination
        val source = Path.of(sourceFilePath)
        val destination = Path.of(destinationFilePath)

        // Use Files.copy to copy the file
        Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING)

        println("File copied successfully from '$sourceFilePath' to '$destinationFilePath'.")
    } catch (e: Exception) {
        println("An error occurred while copying the file: ${e.message}")


File copied successfully from 'example.txt' to 'example_copy.txt'.

In the following screenshot, you could see the copied file 'example_copy.txt'.

Kotlin - Copy File - The copied file highlighted


In this Kotlin File Operations tutorial, we have seen how to copy a file using Files.copy() method of java.nio.files package, with step by step guide, and an example program.