Copy Content of One File to Other File in Kotlin

Learn how to copy content of one file to other file in Kotlin using extension function to Java Class java.io.File, copyTo() with example Kotlin program.

For scenarios to copy a file to other location, overwrite if it already present, or not overwrite if already present, refer the Kotlin example programs given below.

In Kotlin JVM projects, the most direct way to copy a file is to use the copyTo() extension function available on java.io.File. It copies the bytes from the source file to the target file. You can decide whether an existing target file should be overwritten and, when needed, specify a buffer size for the copy operation.

Kotlin File.copyTo() Syntax for Copying File Content

The syntax of File.copyTo() method is

</>
Copy
fun File.copyTo(
        ?target: File,
        ?overwrite: Boolean = false,
        ?bufferSize: Int = DEFAULT_BUFFER_SIZE
): File

Use the following valid Kotlin form when writing the function signature in your notes or code comments.

</>
Copy
fun File.copyTo(
    target: File,
    overwrite: Boolean = false,
    bufferSize: Int = DEFAULT_BUFFER_SIZE
): File

A simple example to use File.copyTo() is

</>
Copy
File("source_file").copyTo(File("target_file"), overwrite, bufferSize);

In practice, you normally pass a source File, a target File, and optionally the overwrite flag.

</>
Copy
import java.io.File

fun main() {
    val source = File("file.txt")
    val target = File("target_file.txt")

    source.copyTo(target, overwrite = true)
}

where

ParameterRequired/OptionalDescription
source_fileREQUIREDSource file name
target_fileREQUIREDTarget file name
overwriteOPTIONALboolean value : if true, overwrites the file, else not. The default value is false and hence does not overwrite if the target file is already present.
bufferSizeOPTIONALDefault buffersize depends on the platform. You may provide an other buffersize if required

copyTo() returns the target File. This is useful when you want to continue working with the copied file after the copy operation.

Example 1 – Copy File in Kotlin

In the following example, we copy the contents of file file.txt to the file target_file.txt.

example.kt

</>
Copy
import java.io.File

fun main(args: Array) {
    File("file.txt").copyTo(File("target_file.txt"));
}

After running the program, target_file.txt is created in the same working directory if it does not already exist. Its content will be the same as the content of file.txt.

A modern Kotlin version of the same example is shown below.

</>
Copy
import java.io.File

fun main() {
    val sourceFile = File("file.txt")
    val targetFile = File("target_file.txt")

    sourceFile.copyTo(targetFile)
}

Example 2 – Overwrite Target File if Already Present

At times, the target file could be already present. In such scenarios, we can overwrite the content of destination file, by passing true as second argument to copyTo() method.

In this example, we have target_file.txt already present.

example.kt

</>
Copy
import java.io.File

fun main(args: Array) {
    File("file.txt").copyTo(File("target_file.txt"), true);
}

The previous contents of target_file.txt are cleared, and the contents of file.txt will be copied to target_file.txt.

You can also write the overwrite argument with a named parameter. This is easier to read in production code.

</>
Copy
import java.io.File

fun main() {
    val sourceFile = File("file.txt")
    val targetFile = File("target_file.txt")

    sourceFile.copyTo(targetFile, overwrite = true)
}

Example 3 – Do not Overwrite if Target
File Exists

We can also not copy the contents of this file to target file, if the target file is already present. For that, we have to pass false as second argument to copyTo() method.

example.kt

</>
Copy
import java.io.File

fun main(args: Array) {
    File("file.txt").copyTo(File("target_file.txt"), false);
}

If target_file.txt already exists and overwrite is false, Kotlin throws a FileAlreadyExistsException. Therefore, use this option when you want to protect an existing target file from being replaced accidentally.

</>
Copy
import java.io.File

fun main() {
    val sourceFile = File("file.txt")
    val targetFile = File("target_file.txt")

    try {
        sourceFile.copyTo(targetFile, overwrite = false)
        println("File copied successfully.")
    } catch (e: FileAlreadyExistsException) {
        println("Target file already exists: ${targetFile.name}")
    }
}

Check Source File Before Copying Content in Kotlin

Before copying, it is often better to check whether the source file exists and is actually a file. This avoids unclear errors when the path is wrong or when the path points to a directory.

</>
Copy
import java.io.File

fun main() {
    val sourceFile = File("file.txt")
    val targetFile = File("backup/target_file.txt")

    if (!sourceFile.exists()) {
        println("Source file does not exist.")
        return
    }

    if (!sourceFile.isFile) {
        println("Source path is not a regular file.")
        return
    }

    targetFile.parentFile?.mkdirs()
    sourceFile.copyTo(targetFile, overwrite = true)

    println("Copied ${sourceFile.name} to ${targetFile.path}")
}

The line targetFile.parentFile?.mkdirs() creates the target directory if it is missing. This is useful when you copy a file into a folder such as backup, output, or downloads.

Copy a File to Another Folder in Kotlin

To copy a file to another folder, include the destination directory in the target path. The target path must include the final file name, not only the folder name.

</>
Copy
import java.io.File

fun main() {
    val sourceFile = File("reports/monthly_report.txt")
    val destinationFile = File("backup/monthly_report.txt")

    destinationFile.parentFile?.mkdirs()
    sourceFile.copyTo(destinationFile, overwrite = true)
}

If you want to keep the same file name, you can build the target file from the destination directory and the source file name.

</>
Copy
import java.io.File

fun main() {
    val sourceFile = File("reports/monthly_report.txt")
    val destinationDirectory = File("backup")

    destinationDirectory.mkdirs()

    val destinationFile = File(destinationDirectory, sourceFile.name)
    sourceFile.copyTo(destinationFile, overwrite = true)
}

Use Buffer Size While Copying Large Files in Kotlin

The third argument of copyTo() is bufferSize. In most small and medium file-copy tasks, the default buffer size is sufficient. For a large file-copy operation, you may pass a custom buffer size after testing it for your environment.

</>
Copy
import java.io.File

fun main() {
    val sourceFile = File("large-video.dat")
    val targetFile = File("backup/large-video.dat")

    targetFile.parentFile?.mkdirs()

    sourceFile.copyTo(
        target = targetFile,
        overwrite = true,
        bufferSize = 64 * 1024
    )
}

Changing the buffer size does not change the copied content. It only changes how many bytes are read and written in each internal copy step.

Kotlin File.copyTo() Exceptions to Handle

File copying can fail for several practical reasons: the source file may not exist, the target file may already exist, the app may not have permission to read or write the path, or the target disk may not have enough space. Use exception handling when the copy operation is part of a user-facing application.

SituationPossible resultHow to avoid or handle it
Source file path is wrongNoSuchFileException or related file errorCheck exists() and isFile before copying.
Target file already existsFileAlreadyExistsException when overwrite = falsePass overwrite = true only when replacement is intended.
Target folder does not existCopy operation may failCreate the parent folder using parentFile?.mkdirs().
No read or write permissionSecurity or access-related exceptionUse a writable location and handle permission rules for the platform.
Source path is a directoryThe operation is not a regular file copyUse isFile for a single file or a recursive approach for directories.

A safer copy function can return true or false depending on whether the copy operation succeeded.

</>
Copy
import java.io.File
import java.io.IOException

fun copyFileSafely(source: File, target: File, overwrite: Boolean = false): Boolean {
    return try {
        if (!source.exists() || !source.isFile) return false

        target.parentFile?.mkdirs()
        source.copyTo(target, overwrite = overwrite)
        true
    } catch (e: IOException) {
        false
    } catch (e: SecurityException) {
        false
    }
}

fun main() {
    val copied = copyFileSafely(
        source = File("file.txt"),
        target = File("backup/file.txt"),
        overwrite = true
    )

    println("Copied: $copied")
}
Copied: true

Copy File Content Using Kotlin NIO Path.copyTo()

Kotlin also provides file-copy support for Path in the kotlin.io.path package. This style is useful when your project already uses Java NIO paths.

</>
Copy
import kotlin.io.path.Path
import kotlin.io.path.copyTo

fun main() {
    val sourcePath = Path("file.txt")
    val targetPath = Path("backup/file.txt")

    sourcePath.copyTo(targetPath, overwrite = true)
}

For simple JVM programs, File.copyTo() is usually enough. Use Path.copyTo() when you prefer the NIO path API or when the surrounding code already uses Path.

Common Mistakes While Copying Files in Kotlin

  • Passing only a folder as the target: copyTo() expects the target file path. Use File(destinationFolder, sourceFile.name) when you want to copy into a folder.
  • Forgetting the overwrite flag: By default, overwrite is false. If the target file already exists, the copy will fail instead of replacing it.
  • Not creating the destination directory: Create missing folders with parentFile?.mkdirs() before copying.
  • Trying to copy a directory as a file: copyTo() is for a file copy. Directory copying needs separate recursive logic.
  • Ignoring exceptions in apps: In desktop, server, and Android apps, always handle failed copy operations gracefully.

Quick Reference for Kotlin copyTo()

RequirementKotlin code
Copy only if target does not existsource.copyTo(target)
Overwrite target filesource.copyTo(target, overwrite = true)
Use a custom buffer sizesource.copyTo(target, overwrite = true, bufferSize = 64 * 1024)
Create target folder firsttarget.parentFile?.mkdirs()
Keep same file name in another foldersource.copyTo(File(folder, source.name), overwrite = true)

FAQs on Copying Content of One File to Another File in Kotlin

How do I copy the contents of one file to another file in Kotlin?

Use File("source.txt").copyTo(File("target.txt")). This copies the content of source.txt into target.txt if the target file does not already exist.

How do I overwrite the target file while copying in Kotlin?

Pass overwrite = true to copyTo(). For example, source.copyTo(target, overwrite = true) replaces the existing target file content with the source file content.

What happens if the target file already exists and overwrite is false?

The copy operation fails with a file-already-exists error. The default value of overwrite is false, so you must explicitly pass true when replacement is required.

Can Kotlin copy a file into a folder using copyTo()?

Yes, but the target must be a file path. For example, use File(folder, source.name) as the target file when you want to copy the file into another folder with the same name.

Should I use File.copyTo() or Path.copyTo() in Kotlin?

Use File.copyTo() when your code works with java.io.File. Use Path.copyTo() from kotlin.io.path when your code is already based on Java NIO Path.

QA Checklist for This Kotlin File Copy Tutorial

  • Confirm every new Kotlin code block uses a PrismJS-compatible language-kotlin class.
  • Check that the tutorial explains both overwrite = true and the default overwrite = false behavior.
  • Verify that file paths in examples include the final target file name, not only the destination folder.
  • Confirm that examples using a nested target path create the parent directory before copying.
  • Keep the distinction between File.copyTo() and Path.copyTo() clear for JVM Kotlin readers.

Conclusion

In this Kotlin Tutorial – Kotlin Copy File, we have learnt to use File.copyTo() to copy file with an example program.

For normal file-copy tasks, use source.copyTo(target). Pass overwrite = true only when replacing the target file is intended. For safer code, check that the source file exists, create the target folder if required, and handle copy failures with exception handling.