2013-10-08 16 views
1

摘要:具有字節圖像的a.zip包含a.txt,我怎樣才能得到一個乾淨的,正確的閱讀器,返回文本文件的行?一種從壓縮文本文件中獲取文本行的讀者

我確實從網絡服務下載了一個zip文件的圖像到byte[] content。我想寫出這樣

private BufferedReader contentToBufferedReader(byte[] content) 

的方法,將返回一個可到目前爲止,使用像

reader = contentToBufferedReader(content); 
while ((line = reader.readLine()) != null) { 
    processThe(line); 
} 
reader.close() 

一個讀者,我有(更新

private BufferedReader contentToBufferedReader(byte[] content) { 

    ByteArrayInputStream bais = new ByteArrayInputStream(content); 
    ZipInputStream zipStream = new ZipInputStream(bais); 
    BufferedReader reader = null; 

    try { 
     ZipEntry entry = zipStream.getNextEntry(); 

     // I need only the first (and the only) entry from the zip file. 
     if (entry != null) { 
      reader = new BufferedReader(new InputStreamReader(zipStream, "UTF-8")); 
      System.out.println("contentToBufferedReader(): success"); 
     } 
    } 
    catch (IOException e) { 
     System.out.println("contentToBufferedReader(): failed..."); 
     System.out.println(e.getMessage()); 
    } 

    return reader; 
} 

我我不確定如何在失敗時關閉所有的流對象。此外,如果reader已成功返回,使用和關閉,我不確定如何關閉它們。

+2

可能的重複[閱讀文本文件在一個zip存檔](http://stackoverflow.com/questions/4473256/reading-text-files-in-a-zip-archive) –

+0

謝謝,卡佳,提示如何裝飾' zipStream'。我修改了這個問題,因此不應該將它視爲您提到的問題的重複。 – pepr

回答

1

這將讓該字節的所有一氣呵成(用來方便番石榴字節流)

ZipEntry entry = zipStream.getNextEntry(); 
while (entry != null) { 
    if (!entry.isDirectory()) { 
    String filename = entry.getName();//this includes the path! 
    byte[] data = ByteStreams.toByteArray(zipStream); 
    //do something with the bytes 
    } 
    entry = zipIn.getNextEntry(); 
} 

你可以得到一個閱讀器這樣的:

InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(data))); 

的zipStream當您調用zipStream.getNextEntry()時會前進。我也認爲該流不支持標記和重置iirc,這意味着您只能讀取一次(因此在將它傳遞給可能需要隨機訪問的其他處理之前將其全部取出)

+0

+1感謝您教給我'entry.isDirectory()'。否則,如果我可以避免它,我寧願不將'zipStream'的內容提取到'byte []'。另外,我寧願只在一個地方調用'zipStream.getNextEntry()' - 在'while'條件下。 – pepr

+0

很高興幫助。請注意,即使您不一次拉出所有字節,請確保您只能從中讀取一次。我做了噩夢發現。 – tom

1

檢查此主題,您可能需要先解壓縮文件,然後再讀取它。

What is a good Java library to zip/unzip files?

+0

+1鏈接。我發現'zip4j'可能是Android標準zip支持的一個很好的選擇。看起來,我得到的zip文件使用zip64,這是'ZipInputStream'不支持的。 – pepr