如何从jar资源中提取目录(和子目录)? [英] How to extract directory (and sub directories) from jar resource?

查看:185
本文介绍了如何从jar资源中提取目录(和子目录)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

推荐答案

以下代码在这里工作正常:(Java7)

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
}

这篇关于如何从jar资源中提取目录(和子目录)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆