从InputStream解压缩文件并返回另一个InputStream
我正在尝试编写一个函数,它将接受带有压缩文件数据的InputStream
,并返回另一个带有解压缩数据的InputStream
。
压缩文件只包含一个文件,因此不需要创建目录等…
我试着看看ZipInputStream
和其他人,但我对Java中的这么多不同类型的ZipInputStream
到困惑。
概念
GZipinputstream用于将流(或文件)划分为gzip(“.gz”扩展名)。 它没有任何标题信息。
GZipInputStream is for [zippeddata]
如果你有一个真正的zip文件,你必须使用ZipFile打开文件,询问文件列表(在你的例子中一个)并要求解压缩的输入流。
ZipFile is for a file with [header information + zippeddata]
如果您有该文件,您的方法将类似于:
// 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。 它读取包含标题数据的流。
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() } } }
如果您可以更改输入数据,我建议您使用GZIPInputStream
。
GZipInputStream
与ZipInputStream
不同,因为它里面只有一个数据。 所以整个输入流代表整个文件。 在ZipInputStream
,整个流还包含其中的文件结构,可以是很多。
它是使用scala语法:
def unzipByteArray(input: Array[Byte]): String = { val zipInputStream = new ZipInputStream(new ByteArrayInputStream(input)) val entry = zipInputStream.getNextEntry IOUtils.toString(zipInputStream, StandardCharsets.UTF_8) }
除非我遗漏了什么,否则你应该绝对尝试让ZipInputStream
工作,没有理由它不应该(我肯定曾多次使用它)。
你应该做的是尝试让ZipInputStream
工作,如果你不能,发布代码,我们将帮助你解决你遇到的任何问题。
无论你做什么,都不要试图重塑它的function。