简体   繁体   English

如何从jar中的资源中获取文件或目录列表?

[英]How can I get file or directory list from the resources in the jar?

在此处输入图像描述 How can I get file or directory list from the resources in the jar?如何从jar中的资源中获取文件或目录列表?
such as [insights,openapi]例如 [insights,openapi]
such as [20221102.json, 20221103.json].例如 [20221102.json, 20221103.json]。

A jar is actually a zip. Use a lib to read the zip file content.一个jar其实就是一个zip,用一个lib读取zip文件内容。 The read zip code, getZipFileList读取zip代码,getZipFileList

String path = Application.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        log.info("path: " + path);
        String replace = path.replace("/classes", "");
        if (!replace.contains("/resource-script.jar")) {
            replace = replace + "/resource-script.jar";
        }
        List<String> zipFileList2 = getZipFileList(replace);



public static List<String> getZipFileList(String zipFileName) throws IOException {
    ZipInputStream zipInputStream = null;
    try (FileInputStream inputStream = new FileInputStream(zipFileName)) {
        zipInputStream = new ZipInputStream(
                new BufferedInputStream(inputStream), StandardCharsets.UTF_8);
        java.util.zip.ZipEntry ze;
        List<String> list = new ArrayList<>();

        //循环遍历
        while ((ze = zipInputStream.getNextEntry()) != null) {
            if (!ze.isDirectory()) {
                list.add(ze.getName());
            }
        }
        return list;
    } catch (Exception e) {
        log.info(" getZipOneFileContent error:" + e.getMessage());
        return null;
    } finally {
        if (zipInputStream != null) {
            zipInputStream.closeEntry();
        }
    }
}


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM