Don*_*ing 4 java zipinputstream
我试图在一个zip文件中找到一个文件并将其作为一个文件InputStream.所以这就是我到目前为止所做的事情,我不确定我是否正确地做到了.
这是一个样本,因为原件略长,但这是主要组件......
public InputStream Search_Image(String file_located, ZipInputStream zip)
throws IOException {
for (ZipEntry zip_e = zip.getNextEntry(); zip_e != null ; zip_e = zip.getNextEntry()) {
if (file_located.equals(zip_e.getName())) {
return zip;
}
if (zip_e.isDirectory()) {
Search_Image(file_located, zip);
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
现在我面临的主要问题是,ZipInputStreamin Search_Image与原始组件相同ZipInputStream......
if(zip_e.isDirectory()) {
//"zip" is the same as the original I need a change here to find folders again.
Search_Image(file_located, zip);
}
Run Code Online (Sandbox Code Playgroud)
现在问题是,如何获得ZipInputStream新的zip_entry?如果我在我的方法中做了任何错误,请加入,因为我仍然缺乏这个类的逻辑.
ZipFile如果您还不需要输入流,则应该使用该类而不必担心自己.
ZipFile file = new ZipFile("file.zip");
ZipInputStream zis = searchImage("foo.png", file);
public InputStream searchImage(String name, ZipFile file) {
for (ZipEntry e : Collections.list(file.entries())) {
if (e.getName().endsWith(name)) {
return file.getInputStream(e);
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
一些事实:
Search_Image不好,searchImage是)endsWith(name)因为文件可能位于文件夹中,而zip内的文件名始终包含路径使用访问 zip 条目ZipInputStream显然不是这样做的方法,因为您需要遍历条目以找到它,这不是一种可扩展的方法因为性能将取决于 zip 文件中的条目总数。
为了获得最佳的性能,你需要使用一个ZipFile以直接访问一个条目得益于方法getEntry(name)您归档文件的大小什么的。
public InputStream searchImage(String name, ZipFile zipFile) throws IOException {
// Get the entry by its name
ZipEntry entry = zipFile.getEntry(name);
if (entry != null) {
// The entry could be found
return zipFile.getInputStream(entry);
}
// The entry could not be found
return null;
}
Run Code Online (Sandbox Code Playgroud)
请注意,此处提供的名称是使用作为路径分隔符的存档中图像的相对路径,/因此如果您想访问foo.png目录中的图像bar,则预期名称将为bar/foo.png.
| 归档时间: |
|
| 查看次数: |
11559 次 |
| 最近记录: |