我正在尝试使用 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,否则我会得到异常 - 如果我不想自己计算大小和 crc,我可以使用
DEFLATE
零级别的方法:
那么,在这种情况下我根本没有压缩存档是否正确?zipOutputStream.setMethod(ZipOutputStream.DEFLATED); zipOutputStream.setLevel(ZipOutputStream.STORED);
- 有没有更方便、更直观的方法来创建非压缩档案?
- 如果我设置方法