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