Question
I'm running into a problem using the Commons compress library to create a tar.gz of a directory.
How-To
Below is sample code:
- package howto;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
- import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
- import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
- import org.apache.commons.compress.utils.IOUtils;
- public class TarDirectory {
- private static void AddFileToTarGz(TarArchiveOutputStream tOut, File f, String base) throws IOException {
- String entryName = base + f.getName();
- System.out.printf("\tAdd entry...%s\n", entryName);
- TarArchiveEntry tarEntry = new TarArchiveEntry(f, entryName);
- tOut.putArchiveEntry(tarEntry);
- if (f.isFile())
- {
- IOUtils.copy(new FileInputStream(f), tOut);
- tOut.closeArchiveEntry();
- } else {
- tOut.closeArchiveEntry();
- File[] children = f.listFiles();
- if (children != null){
- for (File child : children)
- {
- AddFileToTarGz(tOut, child, entryName + "/");
- }
- }
- }
- }
- public static void main(String[] args) throws Exception{
- if(args.length<2)
- {
- System.out.printf("\t[Info] Please give argument1 as directory; argument2 as output tar file.\n");
- return;
- }
- File outFile = new File(args[1]);
- File dir = new File(args[0]);
- FileOutputStream fOut=null;
- BufferedOutputStream bOut=null;
- GzipCompressorOutputStream gzOut=null;
- TarArchiveOutputStream tOut=null;
- try{
- fOut = new FileOutputStream(outFile);
- bOut = new BufferedOutputStream(fOut);
- gzOut = new GzipCompressorOutputStream(bOut);
- tOut = new TarArchiveOutputStream(gzOut);
- AddFileToTarGz(tOut, dir , "");
- } finally {
- if(tOut!=null) {
- tOut.finish();
- tOut.close();
- gzOut.close();
- bOut.close();
- fOut.close();
- }
- }
- }
- }
沒有留言:
張貼留言