English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin程序将文本追加到现有文件

Collection d'exemples Kotlin

在该程序中,您将学习将文本附加到Kotlin中现有文件的不同方法。

在将文本追加到现有文件之前,我们假设在src文件夹中有一个名为test.txt的文件。

这是test.txt的内容

This is a
Test file.

Exemple1:将文本追加到现有文件

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块来正确捕获异常。

Exemple2:使用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) {
    }
}

La sortie du programme est comparable à l'exemple1Identique.

Dans le programme ci-dessus, nous n'utilisons pas la méthode write(), mais l'instance (objet) de FileWriter pour ajouter du texte à un fichier existant.

Lors de la création de l'objet FileWriter, nous passons le chemin du fichier et true en tant que second paramètre. true indique qu'il est permis d'ajouter au fichier.

Ensuite, nous utilisons la méthode write() pour ajouter le texte donné et fermons l'écriture dans le fichier.

Voici le code Java équivalent :Programme Java pour ajouter du texte à un fichier existant

Collection d'exemples Kotlin