有 Java 编程相关的问题?

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

java如何读取jar文件中的zip文件

我有一个zip文件(在一个jar文件中),我想读取它。 我知道我可以使用getResourceAsStream(…)轻松读取txt文件,避免错误“urinothierarchy”。 但现在我确定如何为zip文件执行该操作

下面是我的代码,但当我将代码导出到runnable jar并运行它时,它会抛出“URI非层次错误”

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) 个答案

  1. # 1 楼答案

    这可以通过使用扫描仪来完成。例如:

            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())
            {
               ....
            }