jave解压tar包
时间: 2023-11-23 09:57:32 浏览: 32
以下是Java解压tar包的示例代码:
```java
import java.io.*;
import org.apache.commons.compress.archivers.tar.*;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
public class TarExtractor {
public static void extract(String sourceTarPath, String destDirPath) throws IOException {
try (TarArchiveInputStream tarIn = new TarArchiveInputStream(new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(sourceTarPath))))) {
TarArchiveEntry entry;
while ((entry = tarIn.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
File curfile = new File(destDirPath, entry.getName());
File parent = curfile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
try (OutputStream out = new FileOutputStream(curfile)) {
byte[] buffer = new byte[4096];
int read;
while ((read = tarIn.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
}
}
}
}
```
这个示例代码使用了Apache Commons Compress库来解压tar包。你需要将javatar-2.5.jar添加到你的项目中,并在代码中导入相关的类。
调用示例:
```java
String sourceTarPath = "D://test//zipRes//res//test.tar.gz";
String destDirPath = "D://test//zipRes//res//extracted";
TarExtractor.extract(sourceTarPath, destDirPath);
```
其中,sourceTarPath是你要解压的tar包的路径,destDirPath是你要将文件解压到的目录的路径。