如果你正在读取的是 tar 压缩包而不是 tar.gz 压缩包,你可以直接使用 TarArchiveInputStream
进行解压,而无需使用 GzipCompressorInputStream
。下面是相应的修改:
import java.io.IOException;
import java.nio.file.*;
import java.net.URL;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.MessageDigest;
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 Main {
public static void main(String[] args) {
try {
String url = "http://18.0.0.9:8080/test/wf.tar";
String localFileName = "downloadedFile.tar";
String extractedDir = "extractedFiles";
downloadFile(url, localFileName);
extractTar(localFileName, extractedDir);
calculateMD5(extractedDir);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void downloadFile(String url, String localFileName) throws IOException {
try (InputStream in = new URL(url).openStream()) {
Files.copy(in, Paths.get(localFileName), StandardCopyOption.REPLACE_EXISTING);
}
}
private static void extractTar(String archivePath, String destDir) throws IOException {
try (InputStream in = Files.newInputStream(Paths.get(archivePath));
TarArchiveInputStream tarIn = new TarArchiveInputStream(in)) {
TarArchiveEntry entry;
while ((entry = tarIn.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
Path entryPath = Paths.get(destDir, entry.getName());
Files.copy(tarIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
}
}
}
private static void calculateMD5(String directory) throws Exception {
Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
try {
byte[] fileBytes = Files.readAllBytes(file);
String md5 = calculateMD5(fileBytes);
System.out.println("File: " + file.getFileName() + ", MD5: " + md5);
} catch (Exception e) {
e.printStackTrace();
}
return FileVisitResult.CONTINUE;
}
});
}
private static String calculateMD5(byte[] data) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(data);
byte[] mdBytes = md.digest();
// convert the byte to hex format
StringBuilder sb = new StringBuilder();
for (byte mdByte : mdBytes) {
sb.append(Integer.toString((mdByte & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
这里使用了 TarArchiveInputStream
来解压 tar 文件,而不再需要 GzipCompressorInputStream
。确保你的项目中包含了 Apache Commons Compress 库,这是处理 tar 文件的一个常见选择。