Appending to a text file with FileWriter & bufferedWriter

Hi All,

In the following example using FileWriter, two lines are appended to a text file using both the .write() and .append() methods, when the context mode is set to APPEND (true)…


File("test_file2.txt").bufferedWriter().use { out->
   out.write(("Line 1\r\n"))
   out.write(("Line 2\r\n"))
}

FileWriter( "test_file2.txt", true ).use { out ->
   out.write("Appended Line 3\r\n")  // append works here
   out.append("Appended Line 4\r\n") // append works here too!
}

Output
-----------
Line 1
Line 2
Appended Line 3
Appended Line 4

What’s the difference between .write() and .append() in this case?

If the mode is set to “false”, then .write() and .append() will perform as expected (write will overwrite the file, and append will add to it). But if the mode is set to “true”, It just seems superfluous to have .write() append, when .append() does the same thing.

Incidentally, how would you append using bufferedWriter (without using FileWriter) ?

Edit: I’ve just discovered File.appendText() which seems like a very simple way to append to a file. But if it’s so simple to append to a file with .appendText(), why are there so many complicated ways to create files (.bufferedWriter(), .printWriter(), .writeText(), .writeBytes(), Files.write(), etc.), and is appendText() compatible with all the different file types they create?

Thanks!

1 Like

First of all, technically we speak about Java stdlib here, not Kotlin. And I think it has nothing to do with the file mode. write() and append() are almost the same. You need to understand that Java has 26 years and some of its components are there mostly for historic reasons. I’m not sure if this is the case, but it seems to me that append() is just a newer write() - which accepts CharSequence instead of String and allows chaining, because it returns the writer itself. It may be the only reason for duplication.

Also, because Java stdlib is pretty cumbersome, Kotlin provides some utilities to make the life easier. This is e.g. File.appendText() you mentioned. So this is improvement over Java stdlib provided by Kotlin.

3 Likes

Thank you broot. Excellent reply. I forget sometimes that Kotlin suffers from the old, clunky Java baggage, while adding its own more efficient routines to compensate.

Will appendText() be able to append to all files (both text and binary) created by all the other methods, like bufferedWriter(), printWriter(), writeText(), writeBytes(), FileWriter(), etc?

I’m not sure what do you mean. appendText() is an extension over File. It doesn’t work with BufferedWriter, FileWriter, etc. I don’t see why it matters how the file was created.

Also, you can ctrl+click on appendText() to see that it is in fact a very simple utility. it creates FileOutputStream and then writes to it.

1 Like

Great. That answers my question. Thank you again :slight_smile: