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?
File
if you can. See java7fs.wikia.com/wiki/Why_File_sucks – Dudek