Java 将文件打成 tar 包,需要引用如下依赖包。
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
</dependency>
Java 实现方法及测试方法如下所示。
package com.test.utils;
import lombok.extern.slf4j.Slf4j;
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.ArrayList;
import java.util.List;
/**
* 将文件打成 tar 包
*/
@Slf4j
public class PackTar {
/**
* 将一组文件打成 tar 包
*
* @param sources 要打包的原文件数组
* @param target tar 文件
*/
public static Boolean packTar(List<File> sources, File target) {
FileOutputStream out;
try {
out = new FileOutputStream(target);
TarArchiveOutputStream os = new TarArchiveOutputStream(out);
for (File file : sources) {
InputStream inputStream;
// file.getName() 此处如果不填写文件名,则会按照原路径压缩文件
os.putArchiveEntry(new TarArchiveEntry(file, file.getName()));
inputStream = new FileInputStream(file);
IOUtils.copy(inputStream, os);
os.closeArchiveEntry();
}
os.flush();
os.close();
return true;
} catch (FileNotFoundException e) {
log.error("未指定源文件或 tar 文件", e);
return false;
} catch (Exception e) {
log.error("打包文件出现异常", e);
return false;
}
}
/**
* 将单个文件打成 tar 包
*
* @param source 要打包的原文件
* @param target tar 文件
*/
public static Boolean packTar(File source, File target) {
FileOutputStream out;
try {
out = new FileOutputStream(target);
TarArchiveOutputStream os = new TarArchiveOutputStream(out);
InputStream inputStream;
// file.getName() 此处如果不填写文件名,则会按照原路径压缩文件
os.putArchiveEntry(new TarArchiveEntry(source, source.getName()));
inputStream = new FileInputStream(source);
IOUtils.copy(inputStream, os);
os.closeArchiveEntry();
os.flush();
os.close();
return true;
} catch (FileNotFoundException e) {
log.error("未指定源文件或 tar 文件", e);
return false;
} catch (Exception e) {
log.error("打包文件出现异常", e);
return false;
}
}
public static void main(String[] args) {
// 将一组文件打成 tar 包
List<File> listFile = new ArrayList<>();
listFile.add(new File("D:\\20210112\\test210112.txt"));
listFile.add(new File("D:\\20210113\\test210113.txt"));
String fileZip = "D:\\test1.tar";
Boolean result = packTar(listFile, new File(fileZip));
log.info("打包文件结果:{}", result);
// 将单一文件打成 tar 包
Boolean result1 = packTar(new File("D:\\20210114\\test210114.txt"),
new File("D:\\test2.tar"));
log.info("打包文件结果:{}", result1);
}
}