I would like to parse a .zip file. The .zip file contains one folder. The folder in turn contains several files. I would like to read all files without writing the .zip file to disk. I have the following code:
zipFile = new ZipFile(file);
Enumeration extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()){
ZipEntry entry = entries.nextElement();
InputStream stream = zipFile.getInputStream(entry);
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
Scanner inputStream = new Scanner(reader);
inputStream.nextLine();
while (inputStream.hasNext()) {
String data = inputStream.nextLine(); // Gets a whole line
String[] line = data.split(SEPARATOR); // Splits the line up into a string array
}
inputStream.close();
stream.close();
}
zipFile.close();
The problem is that this only works when the files are directly in the .zip file. How can I adapt my code so that it also works when the files are inside a folder in the .zip file?
解决方案
You could put the code that reads content inside an if
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()) {
InputStream stream = zipFile.getInputStream(entry);
...
stream.close();
}