我正在Java中创建一个方法来打开zip文件并动态处理zip文件中的Excel文件.我在Java中使用API ZipFile,并希望在内存中处理zip文件而不将其解压缩到文件系统.
到目前为止,我能够遍历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();
}
}
解决方法:
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();
}
}
}
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;
}