我想解析一个.zip文件. .zip文件包含一个文件夹.该文件夹依次包含几个文件.我想读取所有文件而不将.zip文件写入磁盘.我有以下代码:
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();
问题在于,这仅在文件直接位于.zip文件中时有效.当文件位于.zip文件中的文件夹内时,如何调整代码,使其也起作用?
解决方法:
您可以将读取内容的代码放在if中
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()) {
InputStream stream = zipFile.getInputStream(entry);
...
stream.close();
}