Reading the contents of a file
In this recipe, we are going to retrieve the contents of a file as text and print it to the console. We are going to use the standard library File.readText()
extension function, returning a String
representing the text content of the given File
instance.
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's GitHub repository: https://github.com/PacktPublishing/Kotlin-Standard-Library-Cookbook. In this recipe, we are going to use the file1.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
- Declare a
String
storing a path to the file we are going to read:
val filePahtName = "src${SEPARATOR}main${SEPARATOR}resources${SEPARATOR}file1.txt"
- Instantiate a
File
using the specified path:
val filePahtName = "src${SEPARATOR...