How to extract directory (and sub directories) from jar resource?

百般思念 提交于 2019-12-11 03:38:54

问题


I've a dir (with sub dirs) template that is kept as a resource inside a jar file. During run time I need to extract it (template) to tmp dir change some content and finally publish it as a zipped artifact.

My question is: how to extract this content easily? I was trying getResource() as well as getResourceAsStream()..


回答1:


Following code works fine here: (Java7)

String s = this.getClass().getResource("").getPath();
if (s.contains("jar!")) {
    // we have a jar file
    // format: file:/location...jar!...path-in-the-jar
    // we only want to have location :)
    int excl = s.lastIndexOf("!");
    s = s.substring(0, excl);
    s = s.substring("file:/".length());
    Path workingDirPath = workingDir = Files.createTempDirectory("demo")
    try (JarFile jf = new JarFile(s);){
        Enumeration<JarEntry> entries = jf.entries();
        while (entries.hasMoreElements()) {
            JarEntry je = entries.nextElement();
            String name = je.getName();
            if (je.isDirectory()) {
                // directory found
                Path dir = workingDirPath.resolve(name);
                Files.createDirectory(dir);
            } else {
                Path file = workingDirPath.resolve(name);
                try (InputStream is = jf.getInputStream(je);) {
                    Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
                }
            }
        }
    }
} else {
    // debug mode: no jar
}


来源:https://stackoverflow.com/questions/18310397/how-to-extract-directory-and-sub-directories-from-jar-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!