我正在尝试使用java将目录内容压缩为zip存档。 一切都很好,但我只想澄清一些事实。 这是我用来压缩文件的代码:
public void pack(@Nonnull String archiveName, @Nonnull File outputDir, @Nonnull File targetDir) {
File zipFile = new File(outputDir, "out.zip");
ZipOutputStream zipOutputStream = null;
OutputStream outputStream;
try {
// create stream for writing zip archive
outputStream = new FileOutputStream(zipFile);
zipOutputStream = new ZipOutputStream(outputStream);
// write files recursively
writeFiles(zipOutputStream, targetDir.listFiles(), "");
} catch (IOException e) {
LOGGER.error("IO exception while packing files to archive", e);
} finally {
// close output streams
if (zipOutputStream != null) {
try {
zipOutputStream.close();
} catch (IOException e) {
LOGGER.error("Unable to close zip output stream", e);
}
}
}
}
/**
* Writes specified files and their children (in case of directories) to archive
*
* @param zipOutputStream archive output stream
* @param files which should be added to archive
* @param path path relative of root of archive where files should be placed
*/
private void writeFiles(@Nonnull ZipOutputStream zipOutputStream, @Nullable File[] files, @Nonnull String path) throws IOException {
if (files == null || files.length == 0) {
return;
}
for (File file : files) {
if (file.isDirectory()) {
// recursively add files in this directory
String fullDirectoryName = path + file.getName() + "/";
File[] childFiles = file.listFiles();
if (childFiles != null && childFiles.length > 0) {
// write child files to archive. current directory will be created automatically
writeFiles(zipOutputStream, childFiles, fullDirectoryName);
} else {
// empty directory. write directory itself to archive
ZipEntry entry = new ZipEntry(fullDirectoryName);
zipOutputStream.putNextEntry(entry);
zipOutputStream.closeEntry();
}
} else {
// put file in archive
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
zipOutputStream.putNextEntry(new ZipEntry(path + file.getName()));
ByteStreams.copy(bufferedInputStream, zipOutputStream);
zipOutputStream.closeEntry();
bufferedInputStream.close();
}
}
}
现在有一些问题:
默认情况下是否正确(在我的情况下)我会得到压缩存档(使用Deflate方法)?
如何获得未压缩的存档:
zipOutputStream.setMethod(ZipOutputStream.STORED)
我必须提供大小,压缩大小(是否等于大小?)和crc,否则我将获得异常DEFLATE
方法:
zipOutputStream.setMethod(ZipOutputStream.DEFLATED);
zipOutputStream.setLevel(ZipOutputStream.STORED);
那么,在这种情况下,我根本没有压缩存档吗?答案 0 :(得分:-2)
我没有重新发明轮子,而是认真考虑使用现有的库,例如Apache Ant。创建zip文件的基本习惯是:
Project p = new Project();
p.init();
Zip zip = new Zip();
zip.setProject(p);
zip.setDestFile(new File(outputDir, "out.zip"));
FileSet fs = new FileSet();
fs.setProject(p);
fs.setDirectory(targetDir);
zip.addFileset(fs);
zip.perform();
默认情况下,您将获得压缩存档。对于未压缩的zip,您需要添加的是
zip.setCompress(false);
在setDestFile
之后(事实上在perform
之前的任何地方)。