Stefán Freyr Stefánsson
02/03/2021, 11:07 AMappendText
and appendBytes
but what do I do if I want to append an input stream? There’s copyTo
but that replaces the whole file and I don’t want to read the whole input stream into a byte array (for appendBytes
) because of memory usage. Will I have to handle the buffering myself and write a decorator function (File.appendStream(inputStream: InputStream)
) or does something else exist?Matteo Mirk
02/03/2021, 11:27 AMfile.appendBytes(inputStream.readBytes())
If you want you can encapsulate it in an extension function.Stefán Freyr Stefánsson
02/03/2021, 11:30 AMFile.copyTo
handles buffering for you? I think it does.Matteo Mirk
02/03/2021, 11:43 AMinputStream.buffered().use {
val buffer = ByteArray(4096) // choose size
while (it.read(buffer) != -1 ) {
file.appendBytes(buffer)
}
}
Vampire
02/03/2021, 12:42 PMFileOutputStream(
File("first"),
true
).use { out ->
File("second")
.inputStream()
.use {
it.copyTo(out)
}
}
fun File.appendStream(appendee: File) {
FileOutputStream(this, true).use { out ->
appendee
.inputStream()
.use {
it.copyTo(out)
}
}
}
Stefán Freyr Stefánsson
02/03/2021, 2:05 PM@Test
fun appendToFile() {
val file1 = File("foo")
val file2 = File("bar")
val output = File("foobar")
output.createNewFile()
println("file1[${file1.absolutePath} - ${file1.length()}], file2[${file2.absolutePath} - ${file2.length()}]")
output.appendStream(file1)
output.appendStream(file2)
output.outputStream().close()
println("output: ${output.absolutePath} - ${output.length()}")
}
fun File.appendStream(appendee: File) {
FileOutputStream(this, true).use { out ->
appendee
.inputStream()
.use {
it.copyTo(out)
}
}
}
file1[/Users/stefan/work/gor/quarkus/file-transfer-service/foo - 10], file2[/Users/stefan/work/gor/quarkus/file-transfer-service/bar - 22]
output: /Users/stefan/work/gor/quarkus/file-transfer-service/foobar - 0
Vampire
02/03/2021, 2:22 PMclose
is not necessary due to use
that is like try-with-resources in Java and automatically closes the stream in the endfile1[D:\Sourcecode\other\setup-wsl\foo - 3], file2[D:\Sourcecode\other\setup-wsl\bar - 3]
output: D:\Sourcecode\other\setup-wsl\foobar - 6
Stefán Freyr Stefánsson
02/03/2021, 2:28 PMVampire
02/03/2021, 2:29 PMfun File.appendStream(vararg appendees: File) {
FileOutputStream(this, true).use { out ->
appendees
.forEach { appendee ->
appendee
.inputStream()
.use {
it.copyTo(out)
}
}
}
}
and then output.appendStream(file1, file2)
then it only needs to open the outputstream once, but shouldn't make too much differenceStefán Freyr Stefánsson
02/03/2021, 2:31 PMVampire
02/03/2021, 2:32 PMStefán Freyr Stefánsson
02/03/2021, 2:32 PMVampire
02/03/2021, 2:33 PMStefán Freyr Stefánsson
02/03/2021, 2:33 PMnanodeath
02/03/2021, 5:13 PMSequenceInputStream(is1, is2).copyTo(fos)
.