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 :

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 – Copy file


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


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


Conclusion :

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