Skip to content

Instantly share code, notes, and snippets.

@sasaki-shigeo
Last active April 9, 2019 15:24
Show Gist options
  • Save sasaki-shigeo/8370342 to your computer and use it in GitHub Desktop.
Save sasaki-shigeo/8370342 to your computer and use it in GitHub Desktop.
A sample program of ZipOutputStream and ZipInputStream. This code is ported from Hishidama's Java Zip File Memo. See http://www.ne.jp/asahi/hishidama/home/tech/java/zip.html
import java.io._
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import java.util.zip.ZipInputStream
def encode(zos: ZipOutputStream, files: Seq[File]) {
for (f <- files) {
if (f.isDirectory) {
encode(zos, f.listFiles)
} else {
val ze = new ZipEntry(f.getPath.replace('\\','/'))
zos.putNextEntry(ze)
val is = new BufferedInputStream(new FileInputStream(f))
val buf = new Array[Byte](1024)
var len = is.read(buf)
while (len >= 0) {
zos.write(buf, 0 ,len)
len = is.read(buf)
}
is.close
}
}
}
def zip(destPath: String, srcPath: String) {
val destFile = new File(destPath)
val srcFiles = Array(new File(srcPath))
val zos = new ZipOutputStream(new FileOutputStream(destFile))
try {
encode(zos, srcFiles)
}
finally {
zos.close
}
}
def unzip(srcPath:String) {
val zis = new ZipInputStream(new FileInputStream(srcPath))
val buf = new Array[Byte](1024)
var len = 0
var ze = zis.getNextEntry
while (ze != null) {
if (ze.isDirectory) {
var dir = new File(ze.getName)
dir.mkdir
}
else {
var file = new File(ze.getName)
var os = new BufferedOutputStream(new FileOutputStream(file))
try {
len = zis.read(buf)
while (len >= 0) {
os.write(buf, 0, len)
len = zis.read(buf)
}
}
finally {
os.close
}
}
ze = zis.getNextEntry
}
zis.close
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment