java .tar.gz文件读写_Java解压tar.gz文件,文件中的文件路径乱码
时间: 2023-07-06 22:08:44 浏览: 190
Java可以使用Apache Commons Compress来解压tar.gz文件。以下是一个示例代码:
```java
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import java.io.*;
public class TarGzipExample {
public static void main(String[] args) throws IOException {
File file = new File("example.tar.gz");
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
GzipCompressorInputStream gzis = new GzipCompressorInputStream(bis);
TarArchiveInputStream tais = new TarArchiveInputStream(gzis)) {
TarArchiveEntry entry;
while ((entry = tais.getNextTarEntry()) != null) {
String name = entry.getName();
File outputFile = new File(name);
if (entry.isDirectory()) {
outputFile.mkdirs();
} else {
outputFile.getParentFile().mkdirs();
try (OutputStream out = new FileOutputStream(outputFile);
BufferedOutputStream bos = new BufferedOutputStream(out)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = tais.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
}
}
}
}
}
}
```
在读取tar.gz文件时,文件路径可能会乱码。这是因为tar格式不支持Unicode字符集,因此在保存文件名时会使用一种转换方法。如果文件名中包含非ASCII字符,那么这种转换方法可能会导致文件名乱码。要解决这个问题,可以使用`org.apache.commons.compress.archivers.tar.TarUtils.parseName()`方法来解析文件名。以下是修改后的代码:
```java
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarUtils;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import java.io.*;
public class TarGzipExample {
public static void main(String[] args) throws IOException {
File file = new File("example.tar.gz");
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
GzipCompressorInputStream gzis = new GzipCompressorInputStream(bis);
TarArchiveInputStream tais = new TarArchiveInputStream(gzis)) {
TarArchiveEntry entry;
while ((entry = tais.getNextTarEntry()) != null) {
String name = TarUtils.parseName(entry.getName(), entry.getHeader().nameBytes).toString();
File outputFile = new File(name);
if (entry.isDirectory()) {
outputFile.mkdirs();
} else {
outputFile.getParentFile().mkdirs();
try (OutputStream out = new FileOutputStream(outputFile);
BufferedOutputStream bos = new BufferedOutputStream(out)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = tais.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
}
}
}
}
}
}
```
这个示例代码会在解压缩文件时解析文件名,并在保存文件时使用解析后的文件名。这样可以避免文件名乱码问题。
阅读全文