[英]How do I get multiple InputStreams for each entry of a ZipInputStream, to read from those InputStreams later?
當我們創建一個ZipInputStream
z
時,我們在它上面調用getNextEntry
然后從z
中讀取,以獲取下一個文件的內容。 但是,我需要為這些文件獲取ZipInputStream
以便以后從中讀取。 我怎么做? 只需創建n
ZipInputStreams
,然后在第一個上調用getNextEntry
1 次,在第二個上調用 2 次,...,在第 n 個上調用 n 次? 還有比這更優雅的方法嗎?
我不能只將每個條目讀入一個字節數組,因為當文件很大並且此類文件的最大大小只能是 2 gigs 時,這會消耗太多 RAM(我們不能創建byte[]
數組比 Java 中的大),但我有更大的文件。
寫了這個(雖然它在 scala 中,因為我使用的是 scala,而不是 Java。
import java.io.{FileInputStream, InputStream}
import java.util.Scanner
import java.util.zip.{ZipEntry, ZipFile, ZipInputStream}
import scala.collection.mutable.ListBuffer
object ZipTest {
def main(args: Array[String]): Unit = {
val zipFile = new ZipFile("/path/to/file")
val entries = zipFile.entries()
val listBuffer = new ListBuffer[InputStream]
while (entries.hasMoreElements) {
val entry = entries.nextElement()
if(!entry.isDirectory) {
val stream = zipFile.getInputStream(entry)
listBuffer.addOne(stream)
}
}
// small usage example
var scanner = new Scanner(listBuffer(2))
while(scanner.hasNextLine){
println(scanner.nextLine())
}
scanner = new Scanner(listBuffer(0))
while(scanner.hasNextLine){
println(scanner.nextLine())
}
}
}
我實際上在此處的最佳答案中找到了這種方法: Read Content from Files which is inside Zip file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.