nilTheDev
08/19/2021, 4:49 PMfun main() {
val strs = listOf(
"line1",
"line2"
)
val writer = File("src/main/resources/logging/temp.txt")
.writer()
strs.forEach { writer.appendLine(it) }
writer.close()
}
The temp.txt
file is empty when I run this program.
After that the contents of the temp.txt
file looks something like this,
line1
line2
This is a perfectly reasonable output. However, things go wrong when I run a slightly modified version of the code for the second time.
fun main() {
val strs = listOf(
"line3",
"line4"
)
val writer = File("src/main/resources/logging/temp.txt")
.writer()
strs.forEach { writer.appendLine(it) }
writer.close()
}
This is the new version. But this time the temp.txt
file wasn't empty. It had the output of the first program saved into it.
However, after running the new version the temp.txt
file looks like this,
line3
line4
The contents written by the first program are completely wiped out.
Isn't the temp.txt
file supposed to look like this?
line1
line2
line3
line4
If not then what's even the point of using append
over write
? Isn't append
expected to write new content after the previously added content instead of wiping out and starting afresh?
Or, am I missing something?Klitos Kyriacou
08/19/2021, 5:01 PMwriter()
extension to java.io.File
. This extension creates a new java.io.FileWriter
which it constructs without the append
argument, so that this FileWriter truncates the file. The append
method you're calling comes from the FileWriter's Appendable
interface - nothing to do with appending to the file.nilTheDev
08/19/2021, 5:05 PMPaul Griffith
08/19/2021, 5:05 PMStandardOpenOption.APPEND
as an `OpenOption`:
val writer = Path("C:/Users/pgriffith/Downloads/test.txt")
.writer(options = arrayOf(StandardOpenOption.APPEND))
nilTheDev
08/19/2021, 5:07 PMTomasz Krakowiak
08/19/2021, 5:18 PMephemient
08/19/2021, 5:20 PMPaul Griffith
08/19/2021, 5:20 PMwriter
extension is already significantly nicer than the Files
static method you'd use in plain Javaephemient
08/19/2021, 5:21 PMappend: Boolean
parameterephemient
08/19/2021, 5:22 PM.use { }
(equivalent to try-with-resources in Java) to auto-close at the end of the block, and consider using .buffered
Paul Griffith
08/19/2021, 5:23 PMpath.appendLines()
public inline fun Path.appendLines(lines: Iterable<CharSequence>, charset: Charset = Charsets.UTF_8): Path {
Paul Griffith
08/19/2021, 5:25 PM