我正在尝试使用ZipOutPutStream压缩文件。我尝试了以下代码,并获得了包含文件的压缩文件夹。但是,当我使用7Zip提取文件夹时,缺少fileName扩展名。 另外,我无法通过Windows中提供的常规“提取”选项来提取文件夹。
下面是我使用Java -8尝试过的代码
public void compress(字符串压缩,字符串原始){
Path pCompressed = null;
try {
pCompressed = Files.createFile(Paths.get(compressed));
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(pCompressed))) {
Path pRaw = Paths.get(raw);
Files.walk(pRaw).filter(path -> !Files.isDirectory(path)).forEach(path -> {
ZipEntry zipEntry = new ZipEntry(pRaw.relativize(path).toString());
try {
zos.putNextEntry(zipEntry);
Files.copy(path, zos);
zos.closeEntry();
} catch (IOException e) {
logger.error("Exception while copying file to compressed Directory: "+e);
}
});
}
catch(IOException ioe) {
logger.error("Exception while compressing the output file: "+ioe);
}
}
catch (IOException e1) {
logger.error("Exception While Path initialization for compressing the file");
}
}
期望:提取出someFolder / MyFile.csv
答案 0 :(得分:0)
我刚刚尝试了这段代码,当我为它提供compressed = "out.zip"
和raw = "testdir"
时,它对我来说很好用。它生成了一个包含testdir
内容的zip文件。然后,我可以使用7Zip提取该文件,并使用内置的Windows提取文件,文件全部存在并且正确。
我的猜测是您尚未为输出文件指定.zip
扩展名,或者Windows在文件夹视图中隐藏了该扩展名。 (我认为默认情况下会这样做。)