假设我有一个名为Bundles.zip的.zip文件,并且直接在Bundles.zip内部,有一些文件和一些文件夹。.zip如下所示:
现在,我想从Bundles文件夹中提取一切。我的程序已经知道从中提取文件所需的文件夹名称,在本例中为Bundles。
该软件包的zip文件夹里面可以有文件,子文件夹,文件的子文件夹,任何事情,就像这样:
我只需要将所有内容从Bundles文件夹提取到输出目录即可。
如何在Java中完成此操作?我找到了解压缩zip中所有文件和文件夹的答案,但是我只需要解压缩zip中的特定文件夹,而不是所有内容。
到目前为止的工作代码:
ZipFile zipFile = new ZipFile(mapsDirectory + "mapUpload.tmp");
Enumeration zipEntries = zipFile.entries();
String fname;
String folderToExtract = "";
String originalFileNameNoExtension = originalFileName.replace(".zip", "");
while (zipEntries.hasMoreElements()) {
ZipEntry ze = ((ZipEntry)zipEntries.nextElement());
fname = ze.getName();
if (ze.isDirectory()) //if it is a folder
{
if(originalFileNameNoExtension.contains(fname)) //if this is the folder that I am searching for
{
folderToExtract = fname; //the name of the folder to extract all the files from is now fname
break;
}
}
}
if(folderToExtract == "")
{
printError(out, "Badly packaged Unturned map error: " + e.getMessage());
return;
}
//now, how do i extract everything from the folder named folderToExtract?
对于到目前为止的代码,originalFileName类似于“ The Island.zip”。拉链内有一个名为The Island的文件夹。我需要在zip文件中找到与zip文件名称匹配的文件夹,然后提取其中的所有内容。
文件的路径(文件夹)是“ zipEntry.getName()”返回的内容的一部分,它可以为您提供所需的信息,甚至可以了解文件是否位于您要查找的文件夹中。
我会做类似的事情:
while (zipEntries.hasMoreElements()) {
//fname should have the full path
if (ze.getName().startsWith(fname) && !ze.isDirectory())
//it is a file within the dir, and it isn't a dir itself
...extract files...
}
}
ZipFile有一个getInputStream方法来获取给定ZipEntry的输入流,因此,如下所示:
InputStream instream = zipFile.getInputStream(ze);
然后从流中读取字节并将其写入文件。
如果您需要代码将1级以上的代码深入子目录,则可以执行以下操作。显然,这不会编译,但是您可以理解。该方法调用自身,然后返回自身,从而有可能深入所需的子文件夹。
private void extractFiles(String folder) {
//get the files for a given folder
files = codeThatGetsFilesAndDirs(folder);
for(file in files) {
if(file.isDirectory()) {
extractFiles(file.getName());
} else {
//code to extract the file and writes it to disk.
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句