有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

读取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文件中的zip文件

****编辑**** 问题似乎在于sc.nextLine()。toLowerCase()。拆分(“\t”);我发现有几个论坛提到拆分可能会消耗大量内存


共 (1) 个答案

  1. # 1 楼答案

    从zip文件SampleText开始。zip位于java程序的jar文件中,下面的代码将zip文件中的文件解压缩到磁盘。我已经用zip文件中的两个文件对此进行了测试。我将zip文件和类文件放在包/目录中的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);
            }
        }
    }