我正在开发一个需要创建 tar 存档以计算他的哈希的应用程序。但是我遇到了一些问题:
- 不同机器的tar不一样,那么计算出来的hash不一样
- 我无法正确添加目录
- 如果我添加一个 zip 文件,最后,在 tar 中,我的 zip 文件中的内容:/
我已经阅读了 SO 中的不同帖子和关于 apache 的专门教程,以及 apache commons compress jar 的源测试代码,但我没有得到正确的解决方案。
有没有人可以找到我的代码不正确的地方?
public static File createTarFile(File[] files, File repository) {
File tarFile = new File(TEMP_DIR + File.separator + repository.getName() + Constants.TAR_EXTENSION);
if (tarFile.exists()) {
tarFile.delete();
}
try {
OutputStream out = new FileOutputStream(tarFile);
TarArchiveOutputStream aos = (TarArchiveOutputStream) new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
for(File file : files){
Utilities.addFileToTar(aos, file, "");
}
aos.finish();
aos.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return tarFile;
}
private static void addFileToTar(TarArchiveOutputStream tOut, File file, String base) throws IOException {
TarArchiveEntry entry = new TarArchiveEntry(file, base + file.getName());
entry.setModTime(0);
entry.setSize(file.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
entry.setSize(file.length());
tOut.putArchiveEntry(entry);
if (file.isFile()) {
IOUtils.copy(new FileInputStream(file), tOut);
tOut.closeArchiveEntry();
} else {
tOut.closeArchiveEntry();
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
addFileToTar(tOut, child, file.getName());
}
}
}
}
谢谢你。