- 读取所有entry,并输出entry内容:
private void readAllEntries(Path path) throws IOException {
ZipFile zipFile = new ZipFile(path.toFile());
try(InputStream inputStream = Files.newInputStream(path)){
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null){
LOG.info("entry={}, is directory={}", zipEntry.getName(), zipEntry.isDirectory());
if(zipEntry.isDirectory()){
continue;
}
final InputStream inputStream1 = zipFile.getInputStream(zipEntry);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream1, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null){
sb.append(line).append(System.getProperty("line.separator"));
}
LOG.info("{}的内容{}", zipEntry.getName(), sb.toString());
bufferedReader.close();
}
zipInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
- 递归读取zip中的zip
public void readZipFileRecursive(final Path zipFile) {
try (final InputStream zipFileStream = Files.newInputStream(zipFile)) {
this.readZipFileStream(zipFileStream);
} catch (IOException e) {
LOG.error("error reading zip file %s!", zipFile, e);
}
}
private void readZipFileStream(final InputStream zipFileStream) {
final ZipInputStream zipInputStream = new ZipInputStream(zipFileStream);
ZipEntry zipEntry;
try {
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
LOG.info("name of zip entry: {}, directory? {}", zipEntry.getName(), zipEntry.isDirectory());
if (!zipEntry.isDirectory() && zipEntry.getName().endsWith(".zip")) {
this.readZipFileStream(zipInputStream); // recursion
}
}
zipInputStream.close();
} catch (IOException e) {
LOG.error("error reading zip file stream", e);
}
}
网友评论