English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在该程序中,您将学习将文本附加到Kotlin中现有文件的不同方法。
在将文本追加到现有文件之前,我们假设在src文件夹中有一个名为test.txt的文件。
这是test.txt的内容
This is a Test file.
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块来正确捕获异常。
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) { } }
A saída do programa é semelhante ao exemplo1Igual.
No programa acima, não usamos o método write(), mas usamos a instância (objeto) FileWriter para adicionar texto ao arquivo existente.
Ao criar o objeto FileWriter, passamos o caminho do arquivo e true como o segundo parâmetro. true indica que é permitido adicionar ao arquivo.
Em seguida, usamos o método write() para adicionar o texto fornecido e fechamos o escritor de arquivo.
Este é o código Java equivalente:Programa Java para Adicionar Texto a Arquivo Existente。