需下载jar包:commons-compress-1.20.jar
直接运行main方法就可以生成如图结果
1.压缩路径可变化
2.此方法可以改为返回tar的byte[] ; 见代码注释
3.注意文件名需要.tar.gz
package com.hp.ngc.service.ws;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
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;
public class TestTar {
public static void main(String[] args) {
try {
ByteArrayOutputStream fOut = new ByteArrayOutputStream();
BufferedOutputStream buffOut = new BufferedOutputStream(fOut);
GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(buffOut);
TarArchiveOutputStream tarOutputStream = new TarArchiveOutputStream(gzOut);
String fileText1 = "文件1";
String fileText2 = "文件2";
String fileText3 = "文件3";
byte[] fileTextByet1 = fileText1.getBytes();
byte[] fileTextByet2 = fileText2.getBytes();
byte[] fileTextByet3 = fileText3.getBytes();
createTarArchiveEntry("testTar/file1/testFile1.text", fileTextByet1, tarOutputStream);
createTarArchiveEntry("testTar/file2/testFile2.text", fileTextByet2, tarOutputStream);
createTarArchiveEntry("testTar/file3/testFile2.text", fileTextByet3, tarOutputStream);
tarOutputStream.finish();
tarOutputStream.close();
// Convert tarOutputStream to byte array and return
gzOut.close();
buffOut.close();
fOut.close();
byte[] tarByte = fOut.toByteArray();//tar文件的byte
String filePath = "E:/testTar/testTar.tar.gz";//生成的文件名后缀需要为.tar.gz
File tarFile = new File("E:/testTar/testTar.tar.gz");
if (!tarFile.getParentFile().exists()) {
tarFile.getParentFile().mkdirs();//没有目录则 创建上级目录
}
tarFile.createNewFile();
FileOutputStream writer = new FileOutputStream(filePath);
writer.write(tarByte);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void createTarArchiveEntry(String fileName, byte[] configData, TarArchiveOutputStream tOut)throws IOException {
ByteArrayInputStream baOut1 = new ByteArrayInputStream(configData);
TarArchiveEntry tarEntry = new TarArchiveEntry(fileName);
tarEntry.setSize(configData.length);
tOut.putArchiveEntry(tarEntry);
byte[] buffer = new byte[1024];
int len;
while ((len = baOut1.read(buffer)) > 0) {
tOut.write(buffer, 0, len);
}
tOut.closeArchiveEntry();
}
}