I absolutely new to Kotlin and seems I just can not get the append-to-file procedure. I have filename given by val path: String = ".....txt" I want a method in my class that takes line: String and appends it at the end of my file (on new line). My test case is: two consequtive calls to method with two different lines for example "foo" and "bar" and I expect file like:
foo
bar
It works if my method looks like this:
fun writeLine(line: String) {
val f = File(path!!)
f.appendText(line + System.getProperty("line.separator"))
}
And it absolutely doesn`t work in any way like this:
fun writeLine(line: String) {
val f = File(path!!)
f.bufferedWriter().use { out->
out.append(line)
out.newLine()
}
}
It rewrites my file with each call so I get only "bar" in my file. It doesn`t work with printWriter either:
fun writeLine(line: String) {
val f = File(path!!)
f.printWriter().use { out->
out.append(line)
}
}
I`ve got the same result as for BufferedWriter. Why? I just can not get it. How do I append with BufferedWriter or PrintWriter?
Both File.bufferedWriter
and File.printWriter
actually rewrite the target file, replacing its content with what you write with them. This is mostly equivalent to what would happen if you used f.writeText(...)
, not f.appendText(...)
.
One solution would be to create a FileOutputStream
in the append mode by using the appropriate constructor FileOutputStream(file: File, append: Boolean)
, for example:
FileOutputStream(f, true).bufferedWriter().use { writer ->
//...
}