Easy file copying
In this recipe, we are going to explore a neat way of copying a file's contents into a new file. We are going to obtain a sample File
instance from the specified path and copy its content into the new file. Finally, we are going to print the contents of both files to the console to verify the operation.
Getting ready
Make sure you have a sample non-empty file included in your project to read its contents. You can clone the sample project provided with the book at the GitHub repository: https://github.com/PacktPublishing/Kotlin-Standard-Library-Cookbook. In this recipe, we are going to use the file2.txt
file located in the src/main/resources
directory in the sample project.
How to do it...
- Import the
File.separator
constant and assign an alias to it:
import java.io.File.separator as SEPARATOR
- Instantiate a
File
instance for the specifiedfile2.txt
path:
val sourceFileName = "src${SEPARATOR}main${SEPARATOR}resources${SEPARATOR}file2.txt"
val sourceFile = File(sourceFileName)
- Create...