java 解压tar文件
时间: 2023-12-20 18:31:59 浏览: 115
以下是使用Java解压tar文件的示例代码:
```java
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;
import java.io.*;
public class TarExtractor {
public static void extractTarFile(String tarFilePath, String destDirectory) throws IOException, ArchiveException {
try (InputStream fileStream = new FileInputStream(tarFilePath);
TarArchiveInputStream tarStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", fileStream)) {
ArchiveEntry entry;
while ((entry = tarStream.getNextEntry()) ! null) {
if (entry.isDirectory()) {
new File(destDirectory, entry.getName()).mkdirs();
} else {
try (OutputStream out = new FileOutputStream(new File(destDirectory, entry.getName()))) {
IOUtils.copy(tarStream, out);
}
}
}
}
}
public static void main(String[] args) {
String tarFilePath = "path/to/your/tar/file.tar";
String destDirectory = "path/to/extract/directory";
try {
extractTarFile(tarFilePath, destDirectory);
} catch (IOException | ArchiveException e) {
e.printStackTrace();
}
}
}
```
阅读全文