原文: https://www.programiz.com/kotlin-programming/examples/string-from-file
在此程序中,您将学习不同的技术来从 Kotlin 中的给定文件集中创建字符串。
从文件创建字符串之前,我们假设在src文件夹中有一个名为test.txt的文件。
这是test.txt的内容
This is aTest file.
示例 1:从文件创建字符串
import java.nio.charset.Charsetimport java.nio.file.Filesimport java.nio.file.Pathsfun main(args: Array<String>) {val path = System.getProperty("user.dir") + "\\src\\test.txt"val encoding = Charset.defaultCharset();val lines = Files.readAllLines(Paths.get(path), encoding)println(lines)}
运行该程序时,输出为:
[This is a, Test file.]
在上面的程序中,我们使用System的user.dir属性获取存储在变量path中的当前目录。 检查 Kotlin 程序以获取当前目录,以获取更多信息。
我们使用defaultCharset()作为文件的编码。 如果知道编码,请使用它,否则使用默认编码是安全的。
然后,我们使用readAllLines()方法从文件中读取所有行。 它采用文件的path及其encoding,并将所有行作为列表返回,如输出所示。
由于readAllLines也可能会引发IOException,因此我们必须这样定义main方法
public static void main(String[] args) throws IOException
示例 2:从文件创建字符串
import java.nio.charset.Charsetimport java.nio.file.Filesimport java.nio.file.Pathsfun main(args: Array<String>) {val path = System.getProperty("user.dir") + "\\src\\test.txt"val encoding = Charset.defaultCharset()val encoded = Files.readAllBytes(Paths.get(path))val lines = String(encoded, encoding)println(lines)}
运行该程序时,输出为:
This is aTest file.
在上述程序中,我们没有获得字符串列表,而是获得了一个包含所有内容的字符串rows。
为此,我们使用readAllBytes()方法从给定路径读取所有字节。 然后,使用默认的encoding将这些字节转换为字符串。
以下是等效的 Java 代码:从文件的内容创建字符串的 Java 程序。
