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
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.
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);
In practice, you normally pass a source File, a target File, and optionally the overwrite flag.
import java.io.File
fun main() {
val source = File("file.txt")
val target = File("target_file.txt")
source.copyTo(target, overwrite = true)
}
where
| Parameter | Required/Optional | Description |
| source_file | REQUIRED | Source file name |
| target_file | REQUIRED | Target file name |
| overwrite | OPTIONAL | boolean 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. |
| bufferSize | OPTIONAL | Default 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
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.
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
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.
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
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.
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.
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.
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.
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.
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.
| Situation | Possible result | How to avoid or handle it |
|---|---|---|
| Source file path is wrong | NoSuchFileException or related file error | Check exists() and isFile before copying. |
| Target file already exists | FileAlreadyExistsException when overwrite = false | Pass overwrite = true only when replacement is intended. |
| Target folder does not exist | Copy operation may fail | Create the parent folder using parentFile?.mkdirs(). |
| No read or write permission | Security or access-related exception | Use a writable location and handle permission rules for the platform. |
| Source path is a directory | The operation is not a regular file copy | Use 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.
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.
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. UseFile(destinationFolder, sourceFile.name)when you want to copy into a folder. - Forgetting the overwrite flag: By default,
overwriteisfalse. 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()
| Requirement | Kotlin code |
|---|---|
| Copy only if target does not exist | source.copyTo(target) |
| Overwrite target file | source.copyTo(target, overwrite = true) |
| Use a custom buffer size | source.copyTo(target, overwrite = true, bufferSize = 64 * 1024) |
| Create target folder first | target.parentFile?.mkdirs() |
| Keep same file name in another folder | source.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-kotlinclass. - Check that the tutorial explains both
overwrite = trueand the defaultoverwrite = falsebehavior. - 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()andPath.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.
TutorialKart.com