- 首先新建一个工程,将压缩需要使用的依赖放入,如下:
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<!--引入文件解压依赖-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.10.5</version>
</dependency>
</dependencies>
- 在本地新建一个文件夹,内含多个需要压缩的文件,我这里放的是多个json文件,如图:

- 将此文件夹压缩为 xxx.tar,上代码
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarOutputStream;
import java.io.*;
public class OnlyUnTar {
public static void main(String[] args) {
OnlyUnTar unTar = new OnlyUnTar();
unTar.tar();
}
public File tar(){
File srcFile = new File("F:\\wjh");
File targetTarFile = new File("F:\\wjh.tar");
TarOutputStream out = null;
boolean boo = false;
try{
out = new TarOutputStream(new BufferedOutputStream(new FileOutputStream(targetTarFile)));
tar(srcFile, out, "", true);
boo = true;
return targetTarFile;
}catch(IOException ex){
throw new RuntimeException(ex);
}finally{
try{
if(out!=null)
out.close();
}catch(IOException ex){
throw new RuntimeException("关闭Tar输出流出现异常",ex);
}finally{
if(!boo && targetTarFile.exists())
targetTarFile.delete();
}
}
}
public static void tar(File file,TarOutputStream out,String dir,boolean boo) throws IOException{
if(file.isDirectory()){
File[] listFile = file.listFiles();
if(listFile.length == 0 && boo){
out.putNextEntry(new TarEntry(dir + file.getName() + "/"));
return;
}else{
for(File cfile: listFile){
tar(cfile,out,dir + file.getName() + "/",boo);
}
}
}else if(file.isFile()){
byte[] bt = new byte[2048*2];
TarEntry ze = new TarEntry(dir+file.getName());
ze.setSize(file.length());
out.putNextEntry(ze);
FileInputStream fis = null;
try{
fis = new FileInputStream(file);
int i=0;
while((i = fis.read(bt)) != -1) {
out.write(bt, 0, i);
}
}catch(IOException ex){
throw new IOException("写入归档文件出现异常",ex);
}finally{
try{
if (fis != null)
fis.close();
out.closeEntry();
}catch(IOException ex){
throw new IOException("关闭输入流出现异常");
}
}
}
}
}
- 压缩结果:

压缩成功