2016-04-20 19:47:29 +02:00
|
|
|
package eu.kanade.tachiyomi.util
|
|
|
|
|
|
|
|
import okio.BufferedSource
|
2020-01-05 17:29:27 +01:00
|
|
|
import okio.buffer
|
|
|
|
import okio.sink
|
2016-04-20 19:47:29 +02:00
|
|
|
import java.io.File
|
|
|
|
import java.io.OutputStream
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Saves the given source to a file and closes it. Directories will be created if needed.
|
|
|
|
*
|
|
|
|
* @param file the file where the source is copied.
|
|
|
|
*/
|
|
|
|
fun BufferedSource.saveTo(file: File) {
|
|
|
|
try {
|
|
|
|
// Create parent dirs if needed
|
|
|
|
file.parentFile.mkdirs()
|
|
|
|
|
|
|
|
// Copy to destination
|
|
|
|
saveTo(file.outputStream())
|
|
|
|
} catch (e: Exception) {
|
|
|
|
close()
|
|
|
|
file.delete()
|
|
|
|
throw e
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Saves the given source to an output stream and closes both resources.
|
|
|
|
*
|
|
|
|
* @param stream the stream where the source is copied.
|
|
|
|
*/
|
|
|
|
fun BufferedSource.saveTo(stream: OutputStream) {
|
|
|
|
use { input ->
|
2020-01-05 17:29:27 +01:00
|
|
|
stream.sink().buffer().use {
|
2016-04-20 19:47:29 +02:00
|
|
|
it.writeAll(input)
|
|
|
|
it.flush()
|
|
|
|
}
|
|
|
|
}
|
2016-04-21 15:31:07 +02:00
|
|
|
}
|