Kotlin append to file
Asked Answered
I

2

19

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?

Intolerance answered 19/11, 2018 at 22:22 Comment(2)
Not directly a solution, but I highly recommend you avoid File if you can. See java7fs.wikia.com/wiki/Why_File_sucksDudek
Thanks! I`ll look into it.Intolerance
A
56

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 ->
    //... 
}
Assignat answered 19/11, 2018 at 22:58 Comment(2)
Thank you! Now I get it. Unfortunately my reputation here is too low and I`m not allowed to make +1 to your answer, but it indeed clears things for me.Intolerance
@Intolerance Your reputation is higher now :)Bulganin
D
0

For what it is worth, I ended up using the following based on a combination of suggestions including the one from "hotkey". I needed for the append to be conditional including a newline to prepare for any future contents.

FileOutputStream(File(fileNameAndPath), isAppendMode).bufferedWriter().use { 
  writer -> writer.write(textToWrite) 
  if (isAppendMode) { writer.newLine() } 
}
Dialyser answered 29/2, 2024 at 14:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.