我正在尝试编写一个函数,该函数将接受带有压缩文件数据的 InputStream
并返回另一个带有解压缩数据的 InputStream
。
压缩后的文件将只包含一个文件,因此不需要创建目录等...
我尝试查看 ZipInputStream
等,但我对 Java 中这么多不同类型的流感到困惑。
最佳答案
概念
GZIPInputStream用于压缩为 gzip(“.gz”扩展名)的流(或文件)。它没有任何标题信息。
This class implements a stream filter for reading compressed data in the GZIP file format
如果你有一个真正的 zip 文件,你必须使用 ZipFile打开文件,询问文件列表(在您的示例中为一个)并询问解压缩的输入流。
如果您有文件,您的方法将类似于:
// 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。它读取包含 header 数据的流。
ZipInputStream is for a stream with [header information + zippeddata]
重要提示:如果您的 PC 中有文件,您可以使用 ZipFile
类随机访问它
这是通过 InputStream 读取 zip 文件的示例:
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()
}
}
}
关于java - 从 InputStream 解压缩文件并返回另一个 InputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2063099/