Я работаю над приложением, которому нужно создать tar-архив, чтобы вычислить его хэш. Но я сталкиваюсь с некоторыми проблемами:
- tar не одинаков на разных машинах, тогда вычисленный хеш отличается
- Я не могу правильно добавлять каталоги
- Если я добавлю zip-файл в конце в tar, у меня будет содержимое из моего zip-файла:/
Я прочитал другой пост в SO и специальный учебник по apache, а также исходный тестовый код сжатой банки apache commons, но я не нашел правильного решения.
Есть ли кто-нибудь, кто может найти, где мой код неверен?
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());
}
}
}
}
Спасибо.
listFiles
может возвращать файлы в другом порядке. Или это может быть кодировка имен файлов. Вы не должны устанавливать размер, конструкторTarEntry
уже делает это (это может быть причиной сбоя добавления каталогов,length
вполне может вернуть › 0 для каталогов). Что, кроме добавления содержимого zip-архива, вы ожидаете при добавлении zip-файла? - person Stefan Bodewig   schedule 03.12.2015