使用 jakarta.commons.compress-1.0.jar
public class Compress {
public static void main(String[] args) throws IOException {
String tarGzPath = "/home/ben/language/java/compress.tar.gz";
String directoryPath = "/home/ben/language/java/Compress.java";
Compress.createTarGzOfDirectory(directoryPath, tarGzPath);
}
/**
* Creates a tar.gz file at the specified path with the contents of the specified directory.
*
* @param dirPath The path to the directory to create an archive of
* @param archivePath The path to the archive to create
* @throws IOException If anything goes wrong
*/
public static void createTarGzOfDirectory(String directoryPath, String tarGzPath) throws IOException {
FileOutputStream fOut = null;
BufferedOutputStream bOut = null;
GzipCompressorOutputStream gzOut = null;
TarArchiveOutputStream tOut = null;
try {
fOut = new FileOutputStream(new File(tarGzPath));
bOut = new BufferedOutputStream(fOut);
gzOut = new GzipCompressorOutputStream(bOut);
tOut = new TarArchiveOutputStream(gzOut);
addFileToTarGz(tOut, directoryPath, "");
} finally {
tOut.finish();
tOut.close();
gzOut.close();
bOut.close();
fOut.close();
}
}
/**
* Creates a tar entry for the path specified with a name built from the base passed in and the file/directory name.
* If the path is a directory, a recursive call is made such that the full directory is added to the tar.
*
* @param tOut The tar file's output stream
* @param path The filesystem path of the file/directory being added
* @param base The base prefix to for the name of the tar file entry
* @throws IOException If anything goes wrong
*/
private static void addFileToTarGz(TarArchiveOutputStream tOut, String path, String base) throws IOException {
File f = new File(path);
String entryName = base + f.getName();
TarArchiveEntry tarEntry = new TarArchiveEntry(f, entryName);
tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
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.getAbsolutePath(), entryName + "/");
}
}
}
}
}
解压看这边博文:http://blog.pigflying.info/2011/06/commons-compresstargz.html
原文出处:http://www.thoughtspark.org/node/53