- pom.xm引入依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
- 工具类
package com.xuexi.utils;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.util.zip.GZIPOutputStream;
public class TarUtils {
public static void compress(String sourceFolder, String tarGzPath) throws IOException {
createTarFile(sourceFolder, tarGzPath);
}
private static void createTarFile(String sourceFolder, String tarGzPath) {
TarArchiveOutputStream tarOs = null;
try {
FileOutputStream fos = new FileOutputStream(tarGzPath);
GZIPOutputStream gos = new GZIPOutputStream(new BufferedOutputStream(fos));
tarOs = new TarArchiveOutputStream(gos);
tarOs.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
addFilesToTarGZ(sourceFolder, "", tarOs);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
tarOs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void addFilesToTarGZ(String filePath, String parent, TarArchiveOutputStream tarArchive) throws IOException {
File file = new File(filePath);
String entryName = parent + file.getName();
tarArchive.putArchiveEntry(new TarArchiveEntry(file, entryName));
if (file.isFile()) {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
IOUtils.copy(bis, tarArchive);
tarArchive.closeArchiveEntry();
bis.close();
} else if (file.isDirectory()) {
tarArchive.closeArchiveEntry();
for (File f : file.listFiles()) {
addFilesToTarGZ(f.getAbsolutePath(), entryName + File.separator, tarArchive);
}
}
}
public static void main(String[] args) throws IOException {
compress("D:\\testFile\\testFile01", "D:\\testFile\\testFile01.tar.gz");
System.out.println("tar.gz文件生成完成。。。。!");
}
}