Read a file in Kotlin
This article covers different ways to read the contents of a file in Kotlin.
1. Using BufferedReader.lines() function
In Kotlin, you can use the BufferedReader.lines() function to get a Stream of lines of text read from BufferedReader.
|
1 2 3 4 5 6 7 8 9 |
import java.io.BufferedReader import java.io.File import java.io.FileReader fun main() { val file = File("/app/logs/january.log") val reader = BufferedReader(FileReader(file, Charsets.UTF_8)) reader.lines().forEach { println(it) } } |
2. Using Files.lines() function
Alternatively, you can use the Files.lines() function to read all lines from a file using the specified charset.
|
1 2 3 4 5 6 7 |
import java.nio.file.Files import java.nio.file.Paths fun main() { val path = Paths.get("/app/logs/january.log") Files.lines(path, Charsets.UTF_8).forEach { println(it) } } |
3. Using Files.readAllLines() function
Another plausible way to read all lines from a file using the specified charset is to use the Files.readAllLines() function.
|
1 2 3 4 5 6 7 |
import java.nio.file.Files import java.nio.file.Paths fun main() { val path = Paths.get("/app/logs/january.log") Files.readAllLines(path, Charsets.UTF_8).forEach { println(it) } } |
4. Using Files.readAllBytes() function
Another alternative is to use the readAllBytes() function, which returns a byte array having the bytes read from the specified file. To get a string out of file contents, you can pass the byte array to the String constructor.
|
1 2 3 4 5 6 7 8 9 10 |
import java.nio.file.Files import java.nio.file.Paths fun main() { val path = Paths.get("/app/logs/january.log") val encoded = Files.readAllBytes(path) var content = String(encoded, Charsets.UTF_8) println(content) } |
5. Using Files.readString() function
Finally, you can also use the Files.readString() function to read all characters from a file into a string using the specified charset.
|
1 2 3 4 5 6 7 8 9 |
import java.nio.file.Files import java.nio.file.Paths fun main() { val filePath = "/app/logs/january.log" var content = Files.readString(Paths.get(filePath), Charsets.UTF_8) println(content) } |
That’s all about reading a file in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)