如何从jar资源中提取目录(和子目录)



我有一个目录(带子目录)模板,它作为资源保存在jar文件中。运行期间当我需要将它(模板)提取到tmp-dir时,更改一些内容,并最终将其作为压缩工件发布。

我的问题是:如何轻松地提取这些内容?我正在尝试getResource()和getResourceAsStream()。。

以下代码在这里运行良好:(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
}

相关内容

最新更新