2017-08-31 74 views
0

我有一個Java應用程序。此應用程序的可執行jar還包含一些zip和文本文件,它們在應用程序啓動時讀取。我可以很容易地處理閱讀文本文件使用在java jar文件中讀取zip文件

getResourceAsStream 

,但問題是閱讀zip文件。

我試着用下面的代碼,但是這只是增加了4次內存使用量。

 // location of the file 
     InputStream is = ChemicalSynonyms.class.getClassLoader().getResourceAsStream(strFileName); 
     ZipInputStream zis = new ZipInputStream(is); 
     ZipEntry ze = zis.getNextEntry(); 
     Scanner sc = new Scanner(zis); 
     String[] wordsArray; 

     while (sc.hasNextLine()) 
     { 
      // split on tab and use only the first column 
      wordsArray = sc.nextLine().toLowerCase().split("\t"); 
      termSet.add(wordsArray[0]); 
     } 

     sc.close(); 
     zis.close(); 
     is.close(); 

如何有效地讀取壓縮文件,該壓縮文件在同一個jar文件中。

****編輯**** 看來問題在於sc.nextLine()。toLowerCase()。split(「\ t」);我發現了幾個論壇,他們提到分裂會導致消耗大量內存。

+0

您正在處理的zip文件有多大?這個過程將膨脹,並將所有「單詞」放入內存中的數組中。如果你正在處理大量的數據,我不確定是否存在咀嚼記憶的問題。 – slambeth

+0

壓縮文件相對較小。總共31MB(壓縮後) – user1631306

+0

我懷疑我沒有使用正確的方法讀取使用掃描儀的zip文件。有沒有更好的方法? – user1631306

回答

1

從位於java程序jar文件中的zip文件SampleText.zip開始,以下代碼將zip文件中的文件解壓縮(解壓縮)到磁盤。我已經用zip文件中的兩個文件測試過了。我把壓縮文件放在package文件的jar文件中。

package readzipfilefromjar; 

import java.lang.Class; 
import java.net.URL; 
import java.io.InputStream; 
import java.util.zip.ZipInputStream; 
import java.util.zip.ZipEntry; 
import java.io.IOException; 
import java.io.BufferedOutputStream; 
import java.io.FileOutputStream; 

/** 
* @author Charles 
* 
* unzips zip file contained in jar 
*/ 
public class ReadZipFileFromJar { 

    public static void main(String[] args) { 
     (new UnZip()).unzip("SampleText.zip"); 
    }  
} 

class UnZip { 

    void unzip(String zipFileNameStr) { 

     final int BUFFER = 2048; 
     Class myClass = this.getClass(); 
     InputStream inStream = myClass.getResourceAsStream(zipFileNameStr);  
     ZipInputStream zis = new ZipInputStream(inStream); 
     ZipEntry ze; 
     try { 
      BufferedOutputStream dest; 
      while((ze = zis.getNextEntry()) != null) { 
       System.out.println("Extracting: " + ze); 
       int count; 
       byte data[] = new byte [BUFFER]; 
       // write the current file to the disk 
       FileOutputStream fos = new FileOutputStream(ze.getName()); 
       dest = new BufferedOutputStream(fos, BUFFER); 
       while ((count = zis.read(data, 0, BUFFER)) != -1) { 
        dest.write(data, 0, count); 
       } 
       dest.flush(); 
       dest.close(); 
      } 
      zis.close(); 
     } 
     catch (IOException e) { 
      System.out.println("IOException: " + e); 
     } 
    } 
} 
+0

當我測試了這個,我把壓縮文件放在package文件夾的jar文件中。 – Charles

+0

我會接受你的回答。但是我發現了我的問題的原因。 Apprantely,Java的「分裂」功能導致一些內存泄漏時,其被稱爲萬次。 – user1631306