<dependency><groupId>org.apache.ant</groupId><artifactId>ant</artifactId><version>1.9.7</version></dependency>
这里得再添加一下
import lombok.experimental.UtilityClass;import org.apache.commons.io.FileUtils;import org.apache.tools.tar.TarEntry;import org.apache.tools.tar.TarOutputStream;import java.io.*;import java.util.zip.GZIPOutputStream;/*** @author shizi* @since 2020/4/30 1:47 PM*/@UtilityClasspublic class TarUtils {/*** 将对应的文件压缩为tar.gz格式** @param inputFilePath xxx/file* @param targetFileName xxx/file.tar.gz*/public void compress(String inputFilePath, String targetFileName) {TarOutputStream out = getTarOutputStream(targetFileName);File inputFile = new File(inputFilePath);tarPack(out, inputFile, inputFile.getName());try {if (null != out) {out.close();}} catch (IOException e) {e.printStackTrace();}}private TarOutputStream getTarOutputStream(String targetFileName) {FileOutputStream fileOutputStream = null;File path = new File(targetFileName).getParentFile();FileOutputStream fos = null;GZIPOutputStream gos = null;if (!path.exists()) {path.mkdirs();}try {fos = new FileOutputStream(targetFileName);gos = new GZIPOutputStream(new BufferedOutputStream(fos));} catch (Throwable e) {System.err.println(e.getMessage());}TarOutputStream out = new TarOutputStream(gos);// 如果不加下面这段,当压缩包中的路径字节数超过100 byte时,就会报错out.setLongFileMode(TarOutputStream.LONGFILE_GNU);return out;}private void tarPack(TarOutputStream out, File inputFile, String base) {if (inputFile.isDirectory()) {packFolder(out, inputFile, base);} else {packFile(out, inputFile, base);}}private void packFolder(TarOutputStream out, File inputFile, String base) {File[] fileList = inputFile.listFiles();try {// 在打包文件中添加路径out.putNextEntry(new org.apache.tools.tar.TarEntry(base + "/"));} catch (IOException e) {System.err.println(e.getMessage());}base = base.length() == 0 ? "" : base + "/";assert fileList != null;for (File file : fileList) {tarPack(out, file, base + file.getName());}}private void packFile(TarOutputStream out, File inputFile, String base) {TarEntry tarEntry = null;try {//getBytes必须设置编码,否则会导致编码错误;tarEntry = new TarEntry(new String(base.getBytes("GBK"), "ISO-8859-1"));} catch (UnsupportedEncodingException e1) {System.err.println(e1.getMessage());}// 设置打包文件的大小,如果不设置,打包有内容的文件时,会报错tarEntry.setSize(inputFile.length());try {out.putNextEntry(tarEntry);} catch (IOException e) {System.err.println(e.getMessage());}try {byte[] wBuf = FileUtils.readFileToByteArray(inputFile);out.write(wBuf);} catch (IOException | NullPointerException e) {e.printStackTrace();} finally {try {out.closeEntry();} catch (IOException e) {e.printStackTrace();}}}}
@Testpublic void test1(){TarUtils.compress("/Users/zhouzhenyong/tem/project/walle", "/Users/zhouzhenyong/tem/project/walle/test.tar.gz");}
参考:
代码借鉴:https://blog.csdn.net/luchaofang/article/details/88698038
