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.

Syntax – File.copyTo()

The syntax of File.copyTo() method is

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

A simple example to use File.copyTo() is

File("source_file").copyTo(File("target_file"), overwrite, bufferSize);

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
ADVERTISEMENT

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

import java.io.File

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

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

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.

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

import java.io.File

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

Conclusion

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