java - 使用 Java 打开另一个存档文件中的存档文件
问题描述
我有一个名为“file.ear”的文件。这个文件包含几个文件,包括一个名为“file.war”的“war”文件(它也是一个档案)。我打算打开一个位于“file.war”中的文本文件。在这一刻,我的问题是从这个“file.war”创建一个 ZipFile 对象的最佳方法是什么
我从“file.ear”创建了一个 ZipFile 对象并迭代了这些条目。当条目是“file.war”时,我尝试创建另一个 ZipFile
ZipFile earFile = new ZipFile("file.ear");
Enumeration(? extends ZipEntry) earEntries = earFile.entries();
while (earEntries.hasMoreElements()) {
ZipEntry earEntry = earEntries.nextElement();
if (earEntry.toString().equals("file.war")) {
// in this line I want to get a ZipFile from the file "file.war"
ZipFile warFile = new ZipFile(earEntry.toString());
}
}
我希望从“file.war”中获得一个 ZipFile 实例,并且标记的行会引发 FileNotFoundException。
解决方案
ZipFile
仅适用于 ... 文件。AZipEntry
只在内存中,不在硬盘上。
你最好使用ZipInputStream
:
- 你把你的包装
FileInputStream
成一个ZipInputStream
- 您可以保留 .war 条目
InputStream
- 您将 .war 依次包装
InputStream
成ZipInputStream
- 您可以保留文本文件条目,阅读其
InputStream
- 对文本做任何你想做的事
InputStream
!
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Snippet {
public static void main(String[] args) throws IOException {
InputStream w = getInputStreamForEntry(new FileInputStream("file.ear"), "file.war");
InputStream t = getInputStreamForEntry(w, "prova.txt");
try (Scanner s = new Scanner(t);) {
s.useDelimiter("\\Z+");
if (s.hasNext()) {
System.out.println(s.next());
}
}
}
protected static InputStream getInputStreamForEntry(InputStream in, String entry)
throws FileNotFoundException, IOException {
ZipInputStream zis = new ZipInputStream(in);
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
if (zipEntry.toString().equals(entry)) {
// in this line I want to get a ZipFile from the file "file.war"
return zis;
}
zipEntry = zis.getNextEntry();
}
throw new IllegalStateException("No entry '" + entry + "' found in zip");
}
}
!
推荐阅读
- tensorflow - 由 TensorFlow2 训练的简单线性回归模型的池性能
- r - R中没有循环的双重求和
- typescript - 忽略 VSCode 中的 DOM 类型
- python - tkinter 将函数转换为类的多实例
- angular - CdkPortal 中的 CdkDragDrop 没有响应
- iis - 强制进程在 IIS 8.5 中以 32 位模式运行
- android - Android单元测试:java.lang.UnsatisfiedLinkError:否
在 java.library.path 中 - string - 带有样式的 Google 脚本字符串
- android - Android Studio 错误格式不正确(无效令牌)
- vuejs2 - 在 vue js 中将函数作为道具传递