在Java中,可以使用Apache Commons Compress库来创建.tar
或.tar.gz
(gzip压缩的tar包)文件。以下是一个示例,演示如何使用该库创建一个包含若干文件和目录的.tar
或.tar.gz
文件:
首先,确保已将Apache Commons Compress库添加到项目依赖中。如果你使用的是Maven,可以在pom.xml
文件中添加以下依赖:
xml
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
</dependency>
</dependencies>
接下来,编写Java代码来创建.tar
或.tar.gz
文件:
java
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TarGzCompressor {
public static void createTarGz(String sourceDir, String destFilePath) throws IOException {
try (OutputStream fOut = Files.newOutputStream(Paths.get(destFilePath));
BufferedOutputStream bOut = new BufferedOutputStream(fOut);
GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(bOut);
TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut)) {
Path sourcePath = Paths.get(sourceDir);
Files.walk(sourcePath).forEach(source -> {
// Skip the source directory itself
if (!source.equals(sourcePath)) {
addEntryToTar(tOut, source, sourcePath);
}
});
tOut.finish();
}
}
private static void addEntryToTar(TarArchiveOutputStream tOut, Path source, Path base) {
String entryName = base.relativize(source).toString();
TarArchiveEntry tarEntry = new TarArchiveEntry(source.toFile(), entryName);
tarEntry.setSize(source.toFile().length());
try {
tOut.putArchiveEntry(tarEntry);
if (source.toFile().isDirectory()) {
tOut.closeArchiveEntry();
return;
}
try (InputStream in = Files.newInputStream(source)) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
tOut.write(buffer, 0, len);
}
}
tOut.closeArchiveEntry();
} catch (IOException e) {
System.err.println("Error adding " + source + " to tar: " + e.getMessage());
}
}
public static void main(String[] args) {
String sourceDir = "source/";
String destFilePath = "archive.tar.gz";
try {
createTarGz(sourceDir, destFilePath);
System.out.println("Tar.gz creation successful.");
} catch (IOException e) {
System.err.println("Error creating tar.gz: " + e.getMessage());
}
}
}
这个示例定义了一个名为TarGzCompressor
的类,其中包含一个静态方法createTarGz
,它接受一个源目录路径和一个目标.tar.gz
文件路径作为参数。函数首先创建一个输出流链,依次包括:
- 目标文件输出流。
- 缓冲输出流,提高写入效率。
- Gzip压缩输出流。
- Tar输出流。
然后,使用Files.walk
遍历源目录及其所有子目录和文件。对于每个文件或目录,创建一个TarArchiveEntry
,并设置其名称为相对于源目录的路径。接着,将条目添加到tar输出流中。如果是目录,仅添加条目信息即可;如果是文件,则还需读取文件内容并写入tar输出流。
在main
方法中,调用createTarGz
函数处理指定的源目录,并将压缩结果保存到指定的.tar.gz
文件。如果压缩过程中发生错误,程序将打印错误信息;否则,显示压缩成功的消息。
这个示例展示了如何使用Apache Commons Compress库创建.tar.gz
文件。如果只需要创建未压缩的.tar
文件,可以去掉Gzip相关的部分,直接创建TarArchiveOutputStream
连接到目标文件输出流。