Read a text file into a string in Kotlin
This post will discuss how to read a text file into a String in Kotlin.
1. Using Files class
We can use the readAllBytes() function to read all the bytes from a file. It takes the path to the file and returns a byte array containing the bytes read from the file. To get output in the string format, pass the byte array to the String constructor with a charset for decoding.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.nio.charset.Charset import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Paths fun readFile(path: String, encoding: Charset): String { val encoded = Files.readAllBytes(Paths.get(path)) return String(encoded, encoding) } fun main() { val filePath = "/sys/data.log" val content = readFile(filePath, StandardCharsets.UTF_8) println(content) } |
To read the contents of a file as a string, we can use the readAllLines() function, which takes the file’s path and optionally accept the charset to be used for decoding. It returns a list of strings, which can be joined together using the joinToString() function to get a single string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.nio.charset.Charset import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Paths fun readFile(path: String, encoding: Charset): String { val lines = Files.readAllLines(Paths.get(path), encoding) return lines.joinToString("") } fun main() { val filePath = "/sys/data.log" val content = readFile(filePath, StandardCharsets.UTF_8) println(content) } |
The Files.readString() function directly reads all characters from a file into a string. It takes a path to the file and optionally accepts the charset to be used. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.nio.charset.Charset import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Paths fun readFile(path: String, encoding: Charset): String { return Files.readString(Paths.get(path), encoding) } fun main() { val filePath = "/sys/data.log" val content = readFile(filePath, StandardCharsets.UTF_8) println(content) } |
2. Using Scanner
Another solution involves constructing a Scanner to scan the specified file using the specified charset. This is demonstrated below, using the use() function that automatically take care of closing the scanner.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.io.File import java.nio.charset.Charset import java.nio.charset.StandardCharsets import java.util.* fun readFile(path: String, encoding: Charset): String { var content = "" Scanner(File(path), encoding.toString()) .use { content = it.useDelimiter("\\A").next() } return content } fun main() { val filePath = "/sys/data.log" val content = readFile(filePath, StandardCharsets.UTF_8) println(content) } |
3. Using FileReader
Another option is to use a FileReader to read the whole file into a character array. This is demonstrated below using the use() function that automatically takes care of closing all resources.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.io.File import java.io.FileReader fun main() { val file = File("/user/data/details.txt") FileReader(file).use { val chars = CharArray(file.length().toInt()) it.read(chars) val fileContent = String(chars) println(fileContent) } } |
4. Using Input Stream
The idea here is to open an input stream of bytes and repeatedly read bytes of data from it into a byte array using its read() function. Then pass the byte array to the String constructor to get the output in string format.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.io.File import java.io.FileInputStream import java.io.InputStream import java.nio.charset.Charset import java.nio.charset.StandardCharsets fun readFile(path: String, encoding: Charset): String { val file = File(path) val inp: InputStream = FileInputStream(file) val bytes = ByteArray(file.length().toInt()) var offset = 0 while (offset < bytes.size) { val result = inp.read(bytes, offset, bytes.size - offset) if (result == -1) { break } offset += result } return String(bytes, encoding) } fun main() { val filePath = "/sys/data.log" val content = readFile(filePath, StandardCharsets.UTF_8) println(content) } |
The following solution makes use of the BufferedReader. Each invocation of the readLine() function would read bytes from the file and convert them into characters.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.io.BufferedReader import java.io.File import java.io.FileInputStream import java.io.InputStreamReader fun readFile(path: String): String { val sb = StringBuilder() val fileStream = FileInputStream(File(path)) val br = BufferedReader(InputStreamReader(fileStream)) var line: String while (br.readLine().also { line = it } != null) { sb.append(line).append(System.lineSeparator()) } return sb.toString() } fun main() { val filePath = "/sys/data.log" val content = readFile(filePath) println(content) } |
That’s all about reading a text file into a String 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 :)