2
我有一个作为资源保存在jar文件中的目录(与子目录)模板。在运行 时,我需要将它(模板)提取到tmp目录中,更改一些内容并最终将其作为压缩的工件发布。如何从jar资源中提取目录(和子目录)?
我的问题是:如何轻松提取此内容?我努力的getResource()以及的getResourceAsStream()..
我有一个作为资源保存在jar文件中的目录(与子目录)模板。在运行 时,我需要将它(模板)提取到tmp目录中,更改一些内容并最终将其作为压缩的工件发布。如何从jar资源中提取目录(和子目录)?
我的问题是:如何轻松提取此内容?我努力的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
}
这似乎是一个http://stackoverflow.com/q问题dublicate /873282分之18247669 – koppor