This post will discuss how to copy the contents of the source file to the specified destination file in Kotlin. The solution will create the destination file if it doesn’t exist, otherwise, the file contents will be copied to the destination file and file attributes can be ignored.

1. Using Files.copy() function

To copy a file to a destination file, we can use Files.copy() function. By default, copying fails if the destination file already exists. Provide the REPLACE_EXISTING option to overcome this behavior.

Download Code

 
If the source and destination point to the same file, the function completes without copying the file.

2. Using Stream

We can even write our own custom logic for copying a file using a FileInputStream and a FileOutputStream. To facilitate copying, we just need a buffer to copy all the bytes from one file to another. This is demonstrated below:

Download Code

 
Note that if the source and destination point to the same file, the file will be truncated.

3. Using FileChannel

We can use the FileChannel#transferFrom() function to transfer bytes from the source file to the destination file, as shown below. However, as with the previous approach, the contents of the file will be deleted if the source and destination are the same.

Download Code

 
Note that copying a file is a non-atomic operation. i.e. the destination file may remain incomplete in case of an I/O error, power loss, process termination, etc.

That’s all about copying a file in java.