从 InputStream 解压缩文件并返回另一个 InputStream [英] Unzipping a file from InputStream and returning another InputStream
问题描述
我正在尝试编写一个函数,该函数将接受带有压缩文件数据的 InputStream
并返回另一个带有解压缩数据的 InputStream
.
I am trying to write a function which will accept an InputStream
with zipped file data and would return another InputStream
with unzipped data.
压缩后的文件将只包含一个文件,因此不需要创建目录等...
The zipped file will only contain a single file and thus there is no requirement of creating directories, etc...
我尝试查看 ZipInputStream
和其他代码,但我对 Java 中这么多不同类型的流感到困惑.
I tried looking at ZipInputStream
and others but I am confused by so many different types of streams in Java.
推荐答案
概念
GZIPInputStream 用于流(或文件)压缩为 gzip(.gz"扩展名).它没有任何标题信息.
GZIPInputStream is for streams (or files) zipped as gzip (".gz" extension). It doesn't have any header information.
该类实现了一个流过滤器,用于读取 GZIP 文件格式的压缩数据
This class implements a stream filter for reading compressed data in the GZIP file format
如果您有真正的 zip 文件,则必须使用 ZipFile 打开文件,询问文件列表(在您的示例中是一个)并询问解压后的输入流.
If you have a real zip file, you have to use ZipFile to open the file, ask for the list of files (one in your example) and ask for the decompressed input stream.
你的方法,如果你有文件,应该是这样的:
Your method, if you have the file, would be something like:
// ITS PSEUDOCODE!!
private InputStream extractOnlyFile(String path) {
ZipFile zf = new ZipFile(path);
Enumeration e = zf.entries();
ZipEntry entry = (ZipEntry) e.nextElement(); // your only file
return zf.getInputStream(entry);
}
使用 .zip 文件的内容读取 InputStream
好的,如果您有 InputStream,则可以使用(如@cletus 所说)ZipInputStream.它读取包含头数据的流.
Ok, if you have an InputStream you can use (as @cletus says) ZipInputStream. It reads a stream including header data.
ZipInputStream 用于带有 [header information + zippeddata] 的流
ZipInputStream is for a stream with [header information + zippeddata]
重要提示:如果您的 PC 中有该文件,您可以使用 ZipFile
类随机访问它
Important: if you have the file in your PC you can use ZipFile
class to access it randomly
这是通过 InputStream 读取 zip 文件的示例:
This is a sample of reading a zip-file through an InputStream:
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Main {
public static void main(String[] args) throws Exception
{
FileInputStream fis = new FileInputStream("c:/inas400.zip");
// this is where you start, with an InputStream containing the bytes from the zip file
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry entry;
// while there are entries I process them
while ((entry = zis.getNextEntry()) != null)
{
System.out.println("entry: " + entry.getName() + ", " + entry.getSize());
// consume all the data from this entry
while (zis.available() > 0)
zis.read();
// I could close the entry, but getNextEntry does it automatically
// zis.closeEntry()
}
}
}
这篇关于从 InputStream 解压缩文件并返回另一个 InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!