package com.ypsx.yppos.utils

import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.OutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

const val BUFFER_SIZE = 2 * 1024
object ZipUtils {

    /**
     * 压缩成ZIP 方法2
     *
     * @param srcFiles 需要压缩的文件列表
     * @param out      压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    @Throws(RuntimeException::class)
    fun toZip(srcFiles: List<File>, out: OutputStream?) {
        val start = System.currentTimeMillis()
        var zos: ZipOutputStream? = null
        try {
            zos = ZipOutputStream(out)
            for (srcFile in srcFiles) {
                val buf = ByteArray(BUFFER_SIZE)
                zos.putNextEntry(ZipEntry(srcFile.name))
                var len: Int
                val inputStream = FileInputStream(srcFile)
                while (inputStream.read(buf).also { len = it } != -1) {
                    zos.write(buf, 0, len)
                }
                zos.closeEntry()
                inputStream.close()
            }
            val end = System.currentTimeMillis()
            println("压缩完成，耗时：" + (end - start) + " ms")
        } catch (e: Exception) {
            throw RuntimeException("zip error from ZipUtils", e)
        } finally {
            if (zos != null) {
                try {
                    zos.flush()
                    zos.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }


}