Skip to content

Instantly share code, notes, and snippets.

@egtra
Created January 12, 2014 18:50
Show Gist options
  • Select an option

  • Save egtra/8388728 to your computer and use it in GitHub Desktop.

Select an option

Save egtra/8388728 to your computer and use it in GitHub Desktop.
大昔、JavaのZIP関係のライブラリを試してみたくて書いたコード。HDDから発掘されたので、せっかくだから公開する。
import java.io.File
import java.io.FileOutputStream
import java.io.FileInputStream
import java.io.BufferedWriter
import java.nio.ByteBuffer
//import java.util.zip.ZipEntry
//import java.util.zip.ZipOutputStream
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream
object Zip {
def readAllBytes(file:File):Array[Byte] = {
val inStream = new FileInputStream(file)
val channel = inStream.getChannel()
val buffer = ByteBuffer.allocate(channel.size.toInt)
channel.read(buffer)
buffer.clear
val bytes = new Array[Byte](buffer.capacity)
buffer.get(bytes)
channel.close
return bytes
}
//def addDirectory(zos:ZipOutputStream, dir:File, zipPath:String):Unit = {
def addDirectory(zos:ZipArchiveOutputStream, dir:File, zipPath:String):Unit = {
dir.listFiles.foreach(f => {
//println(f.getName)
if (f.isDirectory) {
addDirectory(zos, f, zipPath + f.getName + "/")
} else {
//zos.putNextEntry(new ZipEntry(zipPath + f.getName))
zos.putArchiveEntry(new ZipArchiveEntry(zipPath + f.getName))
val bytes = readAllBytes(f)
zos.write(bytes, 0, bytes.length)
zos.closeArchiveEntry
}
});
}
def main(arg:Array[String]):Unit = {
//val zos = new ZipOutputStream(new FileOutputStream("temp.zip"));
val zos = new ZipArchiveOutputStream(new File("test.zip"))
zos.setLevel(9)
zos.setEncoding("MS932")
try {
addDirectory(zos, new File(arg(0)), "")
zos.finish
zos.flush
} finally {
zos.close
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment