java - 如何读取 Zip 文件中的 Zip 文件中的文件内容
问题描述
邮编结构:-
OuterZip.zip--|
|--Folder1---InnerZip.zip--|
|--TxtFile1.txt // Requirement is to read content of txt file
|--TxtFile2.txt // Without extracting any of zip file
现在我可以读取 txt 文件的名称,但不能读取其中的内容。
代码:-
public static void main(String arg[]){
ZipFile zip = new ZipFile("Outer.zip");
ZipEntry ze;
for (Enumeration e = zip.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
ZipInputStream zin = new ZipInputStream(zip.getInputStream(entry));
while ((ze = zin.getNextEntry()) != null)
{
System.out.println(ze.getName()); //Can read names of txtfiles, Not contents
zip.getInputStream(ze); // It is giving null
}
}
}
PS:- 1. 想要在不提取文件系统中的任何 zip 的情况下执行此操作。
2. 已经在 SOF 上看到了一些答案。
解决方案
ZipFile zip = new ZipFile("Outer.zip");
...
zip.getInputStream(ze); // It is giving null
ze
(eg TxtFile1.txt
) 的内容是InnerZip.zip
not的一部分Outer.zip
(由 表示zip
),因此null
.
我会使用递归:
public static void main(String[] args) throws IOException {
String name = "Outer.zip";
FileInputStream input = new FileInputStream(new File(name));
readZip(input, name);
}
public static void readZip(final InputStream in, final String name) throws IOException {
final ZipInputStream zin = new ZipInputStream(in);
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
if (entry.getName().toLowerCase().endsWith(".zip")) {
readZip(zin, name + "/" + entry.getName());
} else {
readFile(zin, entry.getName());
}
}
}
private static void readFile(final InputStream in, final String name) {
String contents = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));
System.out.println(String.format("Contents of %s: %s", name, contents));
}
0. while (...)
我们正在遍历所有条目。
1. ( if (.endsWith(".zip"))
) 如果遇到另一个 zip,我们会递归调用自身 ( readZip()
) 并转到第0 步。
2. ( else
) 否则我们打印文件的内容(假设这里是文本文件)。
推荐阅读
- javascript - 如果它是Javascrict中的正整数,我如何在求和之前检查json数据
- python - 烧瓶缓存删除以特定字符串开头的键
- javascript - react dnd中如何知道源与目的是否不同?
- reactjs - 在 React-redux 应用程序中将 firestore 侦听器放在哪里?
- python - PyGame OR Moviepy - 显示具有透明度的视频
- javascript - react-redux 不调用 fetch 函数
- ios - 如何解码已经具有不同 API 解码逻辑的对象?
- python - 通过在 pandas 中添加匹配的单元格内容来创建新列
- php - 用数组传递值
- rust - 如何通过连接字符串文字来创建新标识符?