[英]Why Source.fromInputStream is working with GZIPInputStream but not with ZipInputStream
我正在嘗試 stream zip 文件。
以下代碼塊按預期逐行打印:
val inputStream = new GZIPInputStream(new FileInputStream("/some/path"))
val source = Source.fromInputStream(inputStream)
for(line <- source.getLines) {
println(line)
}
但是這個沒有任何作用(它甚至沒有退出):
val inputStream = new ZipInputStream(new FileInputStream("/some/path"))
val source = Source.fromInputStream(inputStream)
for(line <- source.getLines) {
println(line)
}
唯一的區別是使用GZIPInputStream
而不是ZipInputStream
。 class 都實現了InputStream
。
我錯過了什么嗎? 或者有什么解決辦法嗎?
Gzip 只是一個壓縮文件,可以在您從Source
讀取時即時解壓縮。 Zip isn't really a stream, it's just one of many java misnomers (take a look at the interface ), it's more like a directory, containing several files, that you can traverse via ZipEntry
, and read each one separately via Source
. 頂層沒有真正的內容,只是一個目錄列表,所以沒有“行”可以通過Source
獲取。
簡而言之,您只需遍歷條目,為每個條目創建一個新的 Source。 像這樣的東西:
Iterator
.continually(zip.getNextEntry)
.takeWhile(_ != null)
.map { e =>
e.getName -> Source.fromInputStream(zip).getLines.toList
}
(這將創建Map
中每個文件的名稱 zip 到其全部內容 n memory,可能,根本不是您想要的,只是通過Source
說明您可以做什么來訪問該內容)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.