Skip to content

Instantly share code, notes, and snippets.

@akhld
Created July 2, 2015 10:54
Show Gist options
  • Save akhld/a9fb24980ebb7921b4bf to your computer and use it in GitHub Desktop.
Save akhld/a9fb24980ebb7921b4bf to your computer and use it in GitHub Desktop.
Zlib compression
import java.util.zip.{Inflater, Deflater} // Zlib library
import java.nio.file.{Files, Paths}
import java.io.{File, FileOutputStream}
object Inf {
def compress(inData: Array[Byte]): Array[Byte] = {
var deflater: Deflater = new Deflater()
deflater.setInput(inData)
deflater.finish
val compressedData = new Array[Byte](inData.size * 2) // compressed data can be larger than original data
val count: Int = deflater.deflate(compressedData)
return compressedData.take(count)
}
def decompress(inData: Array[Byte]): Array[Byte] = {
val inflater = new Inflater()
inflater.setInput(inData)
val decompressedData = new Array[Byte](inData.size * 2)
var count = inflater.inflate(decompressedData)
var finalData = decompressedData.take(count)
while (count > 0) {
count = inflater.inflate(decompressedData)
finalData = finalData ++ decompressedData.take(count)
}
return finalData
}
def main(args: Array[String]) {
val path = args(0)
val byteArray = Files.readAllBytes(Paths.get(path))
val compressedFilePath = "/Users/kamal/compressed"
val decompressedFilePath = "/Users/kamal/decompressed"
val cmpFile = new FileOutputStream(new File(compressedFilePath))
val dmpFile = new FileOutputStream(new File(decompressedFilePath))
val compressedData = compress(byteArray)
val decompressedData = decompress(compressedData)
cmpFile.write(compressedData)
dmpFile.write(decompressedData)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment