package com.example.base.extensions

import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream

/**
 * /**
 * 将inputStream转化为file
 * @param is
 * @param file 要输出的文件目录
*/
public static void inputStream2File(InputStream is, File file) throws IOException {
OutputStream os = null;
try {
os = new FileOutputStream(file);
int len = 0;
byte[] buffer = new byte[8192];

while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
} finally {
os.close();
is.close();
}
}
 */

fun InputStream.toFile(file:File) :Boolean {
    val dir = if (file.isDirectory) file.absolutePath else file.parent?:""
    File(dir).mkdirs()
    var os: OutputStream? = null
    try {
        os = FileOutputStream(file)
        var len = 0
        val buffer = ByteArray(8192)
        while (this.read(buffer).also { len = it } != -1) {
            os.write(buffer, 0, len)
        }
    } catch (e:Exception) {
        return false
    } finally {
        os?.safeClose()
        this.safeClose()
    }

    return true
}