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

时间:2013-08-19 09:22:57

标签: jar resources extract

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

我的问题是:如何轻松提取此内容?我正在尝试getResource()以及getResourceAsStream()..

1 个答案:

答案 0 :(得分:1)

以下代码在这里工作正常:(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
}