2010年9月10日金曜日

groovyとApache Commons Compressでtarファイルに圧縮する

groovyとApache Commons Compressでtarファイルに圧縮するには、以下のコードを実行します。

import org.apache.commons.compress.archivers.tar.*
import org.apache.commons.compress.utils.*

def writeEntries = { aos, base, path ->
if( path.isDirectory() ){
def children = path.listFiles()
if( children.length == 0 ){
// ディレクトリ追加
def fn = path.getAbsolutePath().substring(
base.getAbsolutePath().length()+1).
replace(File.separator,'/')
println("creating...:" + fn)
ent = new TarArchiveEntry(path, fn)
aos.putArchiveEntry(ent)
aos.closeArchiveEntry()
} else {
for(child in path.listFiles()){
call(aos, base, child)
}
}
} else {
// ファイル追加
def fn = path.getAbsolutePath().substring(
base.getAbsolutePath().length()+1).
replace(File.separator,'/')
println("adding...:" + fn)
ent = aos.createArchiveEntry(path, fn)
aos.putArchiveEntry(ent)
IOUtils.copy(new FileInputStream(path), aos, 8192)
aos.closeArchiveEntry()
}
}

taos = new TarArchiveOutputStream(
new FileOutputStream("test.tar"), 8192)
basedir = new File("testdir")
writeEntries(taos, basedir, basedir)
taos.finish()
taos.flush()
taos.close()


動作環境
groovy 1.7.4, JDK6 Update21, Apache Commons Compress 1.1

0 件のコメント:

コメントを投稿