Appending a file
In this recipe, we are going to learn how to easily create a newFile
and write text to it by appending its content a number of times. We are going to use theFile.appendText()
extension function offered by the standard library. Then, we are going to verify whether the file was successfully created and whether it contains the proper content by printing it to the console.
How to do it...
- Import the
File.separator
constant and assign an alias to it:
import java.io.File.separator as SEPARATOR
- Specify the path to the new file we are going to create:
val fileName = "src${SEPARATOR}main${SEPARATOR}resources${SEPARATOR}temp_file"
- Instantiate the file using the specified file path:
val fileName = "src${SEPARATOR}main${SEPARATOR}resources${SEPARATOR}temp_file"
val file = File(fileName)
- Delete the file if it already exists:
val fileName = "src${SEPARATOR}main${SEPARATOR}resources${SEPARATOR}temp_file"
val file = File(fileName)
if (file.exists()) file.delete()
- Append the file with the next String...