在追加文本到现有文件之前,我们假设在 src 文件夹中有一个名为 test.txt 的文件。
这是 test.txt 的内容
This is a Test file.
示例 1:向现有文件追加文本
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
fun main(args: Array<String>) {
val path = System.getProperty("user.dir") + "\\src\\test.txt"
val text = "Added text"
try {
Files.write(Paths.get(path), text.toByteArray(), StandardOpenOption.APPEND)
} catch (e: IOException) {
}
}
当您运行程序时,test.txt 文件现在包含
This is a Test file.Added text
在上面的程序中,我们使用 System
的 user.dir
属性来获取存储在变量 path 中的当前目录。有关更多信息,请查看 获取当前目录的 Kotlin 程序。
同样,要添加的文本存储在变量 text 中。然后,在 try-catch
块中,我们使用 Files
的 write()
方法将文本追加到现有文件中。
write()
方法需要给定文件的路径、要写入的文本以及文件的打开方式。在我们的例子中,我们使用了 APPEND
选项进行写入。
由于 write() 方法可能会返回 IOException
,因此我们使用 try-catch
块来正确捕获异常。
示例 2:使用 FileWriter 向现有文件追加文本
import java.io.FileWriter
import java.io.IOException
fun main(args: Array<String>) {
val path = System.getProperty("user.dir") + "\\src\\test.txt"
val text = "Added text"
try {
val fw = FileWriter(path, true)
fw.write(text)
fw.close()
} catch (e: IOException) {
}
}
该程序的输出与示例 1 相同。
在上面的程序中,我们没有使用 write()
方法,而是使用 FileWriter
的一个实例(对象)将文本追加到现有文件中。
创建 FileWriter
对象时,我们将文件的路径和 true
作为第二个参数传递。true
表示我们允许追加文件。
然后,我们使用 write()
方法追加给定的 text 并关闭 filewriter。
这是等效的 Java 代码:Java 追加文本到现有文件的程序。