【发布时间】:2020-12-15 13:46:54
【问题描述】:
我正在研究将压缩文件转换为常规 java.io.File 的方法,其中所有文件和文件夹的顺序与 zip 中的相同。基本上我只想解压缩压缩文件而不将其内容复制到新目的地。我已经想出了这个功能,到目前为止效果很好,但前提是 zip 中没有文件夹。 zip 中的文件不能是目录,否则我的功能将不起作用,这就是问题所在。
这是我的功能:
File unzip(File zip) throws IOException
{
ZipInputStream zis = new ZipInputStream(new FileInputStream(zip));
//helper directory to store files into while program is running!
File helperDir = Files.createDirectories(Paths.get("zipFile")).toFile();
//helperDir.deleteOnExit();
byte[] buffer = new byte[1024];
for (ZipEntry entry; (entry = zis.getNextEntry()) != null; )
{
if (!entry.isDirectory()) //true if file in zip is not a folder
{
File newFile = new File(helperDir, entry.getName());
//newFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(newFile);
for (int len = zis.read(buffer); len > 0; len = zis.read(buffer))
fos.write(buffer, 0, len);
fos.close();
}
else
{
//What to do if there are folders in zip...
}
}
zis.close();
return helperDir;
}
如何处理 zip 中的文件夹?或者,是否有更好的方法将 zip 转换为 java.io.File?
请帮忙!
【问题讨论】:
标签: java directory zip unzip ziparchive