我正在 Java 中创建一个方法来打开 zip 文件并动态处理 zip 中的 Excel 文件。我正在 Java 中使用 API ZipFile,并且希望按内存中的原样处理 zipfile,而不将其提取到文件系统。
到目前为止,我可以遍历 zip 文件,但无法列出 zip 文件中目录下的文件。Excel 文件可以位于 zip 文件的文件夹中。下面是我当前的代码,在我遇到问题的部分中有注释。任何帮助是极大的赞赏 :)
public static void main(String[] args) {
try {
ZipFile zip = new ZipFile(new File("C:\\sample.zip"));
for (Enumeration e = zip.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) e.nextElement();
String currentEntry = entry.getName();
if (entry.isDirectory()) {
/*I do not know how to get the files underneath the directory
so that I can process them */
InputStream is = zip.getInputStream(entry);
} else {
InputStream is = zip.getInputStream(entry);
}
}
} catch (ZipException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
Zip 条目实际上没有任何关于文件夹或目录的概念,它们都存在于 zip 文件内的同一概念根中。允许将文件组织到“文件夹”中的是 zip 条目的名称。
zip 条目被视为目录只是因为它实际上不包含任何压缩字节并且被标记为目录。
目录条目是一个标记,让您有机会构建需要将使用相同路径前缀的文件提取到的路径。
这意味着,您不需要真正关心目录条目,除了预先创建任何后续文件可能需要的输出文件夹
public static void unzip(final ZipFile zipfile, final File directory)
throws IOException {
final Enumeration<? extends ZipEntry> entries = zipfile.entries();
while (entries.hasMoreElements()) {
final ZipEntry entry = entries.nextElement();
final File file = file(directory, entry);
if (entry.isDirectory()) {
continue;
}
final InputStream input = zipfile.getInputStream(entry);
try {
// copy bytes from input to file
} finally {
input.close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
protected static File file(final File root, final ZipEntry entry)
throws IOException {
final File file = new File(root, entry.getName());
File parent = file;
if (!entry.isDirectory()) {
final String name = entry.getName();
final int index = name.lastIndexOf('/');
if (index != -1) {
parent = new File(root, name.substring(0, index));
}
}
if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {
throw new IOException(
"failed to create a directory: " + parent.getPath());
}
return file;
}
Run Code Online (Sandbox Code Playgroud)