Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin append to file

Tags:

io

append

kotlin

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?

like image 692
user3575511 Avatar asked Nov 19 '18 22:11

user3575511


People also ask

What is append in Kotlin?

Using plus() function A simple solution to append characters to the end of a String is using the + (or += ) operator.

How do I add an element to a list in Kotlin?

To add a single element to a list or a set, use the add() function. The specified object is appended to the end of the collection. addAll() adds every element of the argument object to a list or a set.


1 Answers

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 ->
    //... 
}
like image 105
hotkey Avatar answered Oct 10 '22 08:10

hotkey