[英]How to read files in a .zip file in Java?
I would like to parse a .zip file. 我想解析一个.zip文件。 The .zip file contains one folder.
.zip文件包含一个文件夹。 The folder in turn contains several files.
该文件夹又包含几个文件。 I would like to read all files without writing the .zip file to disk.
我想在不将.zip文件写入磁盘的情况下读取所有文件。 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. 问题是,这仅在文件直接位于.zip文件中时才有效。 How can I adapt my code so that it also works when the files are inside a folder in the .zip file?
我如何调整我的代码,以便当文件位于.zip文件中的文件夹内时它也能正常工作?
You could put the code that reads content inside an if
您可以将读取内容的代码放在
if
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()) {
InputStream stream = zipFile.getInputStream(entry);
...
stream.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.