java 解压tar文件的案例
时间: 2023-07-18 16:37:19 浏览: 56
好的,以下是Java解压tar文件的示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
public class TarGzUtil {
public static void extractTarGzFile(String tarGzFilePath, String destDirectory) throws IOException {
File tarGzFile = new File(tarGzFilePath);
try (InputStream is = new FileInputStream(tarGzFile);
GzipCompressorInputStream gzipIs = new GzipCompressorInputStream(is);
TarArchiveInputStream tarIs = new TarArchiveInputStream(gzipIs)) {
TarArchiveEntry entry = null;
while ((entry = tarIs.getNextTarEntry()) != null) {
String entryName = entry.getName();
if (entry.isDirectory()) {
new File(destDirectory, entryName).mkdirs();
} else {
File outputFile = new File(destDirectory, entryName);
try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
byte[] buffer = new byte[4096];
int read = 0;
while ((read = tarIs.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
}
}
}
}
}
public static void main(String[] args) throws IOException {
String tarGzFilePath = "/path/to/tar.gz";
String destDirectory = "/path/to/destination/dir";
extractTarGzFile(tarGzFilePath, destDirectory);
}
}
```
这个示例代码使用了 Apache Commons Compress 库来解压 tar.gz 文件。在 `extractTarGzFile` 方法中,我们首先创建一个输入流,然后将其传递给 `GzipCompressorInputStream` 和 `TarArchiveInputStream`。接下来,我们遍历 tar 文件中的每个条目,如果是目录,则创建该目录,否则将条目内容写入输出文件。最后,关闭所有的输入和输出流。