Comme le dit le titre. Pour les mémos.
import java.io._
import java.nio.charset.Charset
import java.util.zip.{ZipEntry, ZipOutputStream}
def main(args: Array[String]): Unit = {
zipFolder("file\\folder", "file\\folder.zip", "Shift_JIS")
}
def zipFolder(targetDir: String, outputZip: String, mojiCode: String): Unit = {
val baseFile = new File(targetDir)
val zos = new ZipOutputStream(new FileOutputStream(new File(outputZip)), Charset.forName(mojiCode))
val fileList: Seq[File] = baseFile.listFiles()
zipFileList(zos, fileList, baseFile)
zos.closeEntry()
zos.close()
}
private def zipFileList(zos: ZipOutputStream, fileList: Seq[File], baseFile: File): Unit = {
for (file <- fileList) {
if (file.isDirectory) {
zipFileList(zos, file.listFiles(), baseFile)
} else {
entryZos(file, zos, baseFile)
}
}
}
private def entryZos(targetFile: File, zos: ZipOutputStream, baseFile: File): Unit = {
val entry = new ZipEntry(targetFile.getAbsolutePath.replace(baseFile.getParentFile.getAbsolutePath, "").drop(1))
zos.putNextEntry(entry)
val in = new BufferedInputStream(new FileInputStream(targetFile))
writeZos(zos, in, targetFile)
in.close()
}
private def writeZos(zos: ZipOutputStream, in: BufferedInputStream, targetFile: File) : Unit = {
val readBytes = in.read()
if (readBytes != -1) {
zos.write(readBytes)
writeZos(zos, in, targetFile)
}
}
Recommended Posts