如何在jar文件中读取zip文件

时间:2017-08-19 14:51:59

标签: java

我有一个zip文件(在jar文件中),我想读取init。 我知道我可以使用getResourceAsStream(...)轻松阅读txt文件,避免错误“URI not hierarchical”。 但现在确定如何为zip文件做到这一点。

以下是我的代码,但是当我将代码导出到runnable jar并运行它时,它会抛出“URI not hierachical error”。

URL fileLocation = ChemicalSynonyms.class.getClassLoader().getResource("sciome/workbench/resources/chemicalSynonym/" + strFileName);
        File file = new File(fileLocation.toURI());

        // it is a zip file
        ZipFile zipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        ZipEntry entry = entries.nextElement();
        InputStream is = zipFile.getInputStream(entry);
        BufferedReader buf = new BufferedReader(new InputStreamReader(is));
        String lineJustFetched = null;
        String[] wordsArray;

        // read each line
        lineJustFetched = buf.readLine();

1 个答案:

答案 0 :(得分:0)

可以使用扫描仪完成。例如:

        InputStream is = MainClass.class.getClassLoader().getResourceAsStream(file location with zip file name);
        ZipInputStream zis = new ZipInputStream(is);
        ZipEntry ze = zis.getNextEntry();
        Scanner sc = new Scanner(zis);

        String[] wordsArray;
        while (sc.hasNextLine())
        {
           ....
        }