2014년 4월 5일 토요일

apache commons compress 이용한 TAR 생성

package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

public class CommonCompressTest{

/**
* @param args
*/
public static void main(String[] args) throws Exception {
String tarFilename = "c:\\tmp\\" + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd-HHmmss") + "-" + UUID.randomUUID().toString() + ".tar";
String baseDir = "C:\\tmp\\aa";
makeTar(tarFilename, baseDir, true);
}

public static void makeTar(String tarFilename, String baseDir, boolean removeIt) throws Exception {
final OutputStream os = new FileOutputStream(tarFilename);
TarArchiveOutputStream taos = new TarArchiveOutputStream(os);

List<File> fileList = getFileList(baseDir);
for (int ii = 0; ii < fileList.size(); ii++){
File entryFile = fileList.get(ii);

if (entryFile.isDirectory() == true)
continue;

String entryName = StringUtils.substring(entryFile.getAbsolutePath(), baseDir.length());

// System.out.println(entryName);
// System.out.println(entryFile);

TarArchiveEntry entry = new TarArchiveEntry(entryName);
byte[] buff = null;
if (entryFile.isFile()) {
buff = IOUtils.toByteArray(new FileInputStream(entryFile));
entry.setSize(buff.length);
}
taos.putArchiveEntry(entry);
if (entryFile.isFile()) {
taos.write(buff);
}
taos.closeArchiveEntry();

}
// System.out.println(fileList);
taos.close();
os.close();

System.out.println("baseDir=" + baseDir);
if (removeIt == true) {
org.apache.commons.io.FileUtils.deleteQuietly(new File(baseDir));
}
}

public static List<File> getFileList(String baseDir) {
List<File> fileList = new ArrayList<File>();

        File root = new File(baseDir);
        File[] list = root.listFiles();

        for ( File f : list ) {
            if ( f.isDirectory() ) {
            fileList.add(f);
            List<File> subFileList = getFileList(f.getAbsolutePath() );
            fileList.addAll(subFileList);
//                System.out.println( "Dir:" + f.getAbsoluteFile() );
            }
            else {
            fileList.add(f);
//                System.out.println( "File:" + f.getAbsoluteFile() );
            }
        }


return fileList;
}
}

댓글 없음:

댓글 쓰기