Writing the contents to a file
In this recipe, we are going to learn how to easily create a new File
and write text to it. We are going to use the File.writeText()
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 contents 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)
- Write the text to the file using the
writeText()
function inside theapply
block:
val fileName = "src${SEPARATOR}main${SEPARATOR}resources${SEPARATOR}temp_file" val file = File(fileName) file.apply { val text = "\"No one in the brief history...