Scala压缩解压Zip文件

package com.sm.utils

import java.io.{File, FileInputStream, FileOutputStream, BufferedInputStream}
import java.util.zip.{ZipInputStream, ZipOutputStream, ZipEntry}


/**
  * create by LiuJinHe 2019/10/8
  */
object ZipUtils {

  /**
    * 解压
    */
  def unCompress(zipFilePath: String): Unit = {
    val fis = new FileInputStream(new File(zipFilePath))
    val zis = new ZipInputStream(fis)

    Stream.continually(zis.getNextEntry).takeWhile(_ != null).foreach {
      file =>
        val fos = new FileOutputStream(file.getName)
        val buffer = new Array[Byte](1024)

        Stream.continually(zis.read(buffer)).takeWhile(_ != -1).foreach(fos.write(buffer, 0, _))
        fos.close()
    }

    zis.close()
    fis.close()
  }


  /**
    * 压缩
    */
  def compressFile(srcFilePath: String, destZipPath: String): Unit = {

    val src = new File(srcFilePath)
    if (!src.exists) throw new RuntimeException(srcFilePath + "不存在")

    val srcFile = new File(destZipPath)
    
    val baseDir = ""
    val bis = new BufferedInputStream(new FileInputStream(src))
    val entry: ZipEntry = new ZipEntry(baseDir + srcFile.getName)

    val fos = new FileOutputStream(srcFile)
    val zos = new ZipOutputStream(fos)
    zos.putNextEntry(entry)

    val buffer: Array[Byte] = new Array[Byte](1024)

    Stream.continually(bis.read(buffer)).takeWhile(_ != -1).foreach(zos.write(buffer, 0, _))

    zos.close()
    bis.close()
    fos.close()
  }
}

 

你可能感兴趣的:(Scala)