How do I archive multiple files into a .zip file using scala?

后端 未结 6 1174
孤独总比滥情好
孤独总比滥情好 2020-12-14 19:41

Could anyone post a simple snippet that does this?

Files are text files, so compression would be nice rather than just archive the files.

I have the filename

6条回答
  •  半阙折子戏
    2020-12-14 19:54

    This is a little bit more scala style in case you like functional:

      def compress(zipFilepath: String, files: List[File]) {
        def readByte(bufferedReader: BufferedReader): Stream[Int] = {
          bufferedReader.read() #:: readByte(bufferedReader)
        }
        val zip = new ZipOutputStream(new FileOutputStream(zipFilepath))
        try {
          for (file <- files) {
            //add zip entry to output stream
            zip.putNextEntry(new ZipEntry(file.getName))
    
            val in = Source.fromFile(file.getCanonicalPath).bufferedReader()
            try {
              readByte(in).takeWhile(_ > -1).toList.foreach(zip.write(_))
            }
            finally {
              in.close()
            }
    
            zip.closeEntry()
          }
        }
        finally {
          zip.close()
        }
      }
    

    and don't forget the imports:

    import java.io.{BufferedReader, FileOutputStream, File}
    import java.util.zip.{ZipEntry, ZipOutputStream}
    import io.Source
    

提交回复
热议问题