Kotlin 读取文件教程显示了如何在 Kotlin 中读取文件。 我们展示了几种在 Kotlin 中读取文件的方法。
在本教程中,我们使用File方法读取文件。
本教程提供了五个示例,这些示例在 Kotlin 中读取文件。
thermopylae.txt
The Battle of Thermopylae was fought between an alliance of Greek city-states,led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over thecourse of three days, during the second Persian invasion of Greece.
在示例中,我们使用此文本文件。
Kotlin 使用File.readLines读取文件
File.readLines()读取文件内容为行列表。 不应将其用于大文件。
readfile.kt
package com.zetcodeimport java.io.Filefun main(args: Array<String>) {val fileName = "src/resources/thermopylae.txt"val lines: List<String> = File(fileName).readLines()lines.forEach { line -> println(line) }}
该示例使用File.readLines()读取文件。
Kotlin 使用File.useLines读取文件
File.useLines()读取所有数据作为行列表,并将其提供给回调。 最后关闭读者。
readfile2.kt
package com.zetcodeimport java.io.Filefun main(args: Array<String>) {val fileName = "src/resources/thermopylae.txt"val myList = mutableListOf<String>()File(fileName).useLines { lines -> myList.addAll(lines) }myList.forEachIndexed { i, line -> println("${i}: " + line) }}
该示例读取文件并将其打印到控制台。 我们在输出中添加行号。
val myList = mutableListOf<String>()
可变列表已创建。
File(fileName).useLines { lines -> myList.addAll(lines) }
使用File.useLines(),我们将行列表复制到上面创建的可变列表中。
myList.forEachIndexed { i, line -> println("${i}: " + line) }
使用forEachIndexed(),我们为每行添加一个行号。
Kotlin 使用File.readText读取文件
File.readText()以String的形式获取此文件的全部内容。 不建议在大文件上使用此方法。
readfile3.kt
package com.zetcodeimport java.io.Filefun main(args: Array<String>) {val fileName = "src/resources/thermopylae.txt"val content = File(fileName).readText()println(content)}
在示例中,我们将整个文件读入一个字符串并将其打印到控制台。
Kotlin 使用InputStream读取文件
InputStream是字节的输入流。
readfile4.kt
package com.zetcodeimport java.io.Fileimport java.io.InputStreamimport java.nio.charset.Charsetfun main(args: Array<String>) {val fileName = "src/resources/thermopylae.txt"val myFile = File(fileName)var ins: InputStream = myFile.inputStream()var content = ins.readBytes().toString(Charset.defaultCharset())println(content)}
该示例从File创建InputStream并从中读取字节。 字节转换为文本。
var ins: InputStream = myFile.inputStream()
从File和inputStream()创建一个InputStream。
var content = ins.readBytes().toString(Charset.defaultCharset())
我们使用readBytes()从InputStream读取字节,然后使用toString()将字节转换为文本。
Kotlin 使用readBytes读取文件
readBytes()以字节数组的形式读取文件的全部内容。 不建议在大文件上使用。
readfile5.kt
package com.zetcodeimport java.io.Filefun main(args: Array<String>) {val fileName = "src/resources/thermopylae.txt"val file = File(fileName)var bytes: ByteArray = file.readBytes()bytes.forEachIndexed { i, byte -> (if (i == 0) {print("${byte} ")} else if (i % 10 == 0) {print("${byte} \n")} else {print("${byte} ")})}}
该示例将文本文件读入字节数组。 它将文件以数字形式打印到控制台。
在本教程中,我们展示了如何在 Kotlin 中读取文件。 您可能也对相关教程感兴趣: Kotlin 编写文件教程和 Kotlin Hello World 教程。
