How to 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.

Copy content of one File to other File in Kotlin

Syntax :

Usage :

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

where :

PARAMETERREQUIRED/
OPTIONAL
DESCRIPTION
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

Example Kotlin Program

Example Kotlin Program – Overwrite if the target file is already present

Example Kotlin Program – Do not overwrite if the target file is already present

You may be also interested in reading content of file, or write content to file.