![](/img/trans.png)
[英]Zipping InputStream, returning InputStream (in memory, no file)
[英]Unzipping a file from InputStream and returning another InputStream
我正在嘗試編寫一個函數,該函數將接受帶有壓縮文件數據的InputStream
並返回另一個帶有解壓縮數據的InputStream
。
壓縮文件將只包含一個文件,因此不需要創建目錄等...
我嘗試查看ZipInputStream
和其他內容,但我對 Java 中這么多不同類型的ZipInputStream
到困惑。
概念
GZIPInputStream用於壓縮為 gzip(“.gz”擴展名)的流(或文件)。 它沒有任何標題信息。
該類實現了一個流過濾器,用於讀取 GZIP 文件格式的壓縮數據
如果你有一個真正的 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。 它讀取包含頭數據的流。
ZipInputStream 用於帶有 [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
工作,如果不能,請發布代碼,我們將幫助您解決遇到的任何問題。
不管你做什么,都不要試圖重新發明它的功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.