我正在尝试从我的插件中内置的包的内容填充目录。当bundle是文件系统时,以下代码有效,但当bundle是JAR时失败。
测试URL是否是目录的最佳方法是什么?或者是否有一种完全不同的,更好的方法来从资源包创建文件结构?
static private void bundleCopy(String dir, String destination) throws IOException {
Bundle bundle = com.mds.apg.Activator.getDefault().getBundle();
for (@SuppressWarnings("unchecked")
Enumeration<URL> en = (Enumeration<URL>) bundle.findEntries(dir, "*", true);
en.hasMoreElements();) {
URL url = en.nextElement();
String toFileName = destination + url.getPath().substring(dir.length());
File toFile = new File(toFileName);
InputStream in;
try {
in = url.openStream();
} catch (FileNotFoundException e) {
// this exception get thrown for file system directories but not for jar file ones
if (!toFile.mkdir()) {
throw new IOException("bundleCopy: " + "directory Creation Failed: "
+ toFileName);
}
continue;
}
FileCopy.coreStreamCopy(in, toFile);
}
}
答案 0 :(得分:1)
我找到了答案:
关键是目录的Enumeration条目以'/'结尾。
以下正确区分JAR和文件系统的目录和文件:
static private void bundleCopy(String dir, String destination)
throws IOException, URISyntaxException {
Bundle bundle = com.mds.apg.Activator.getDefault().getBundle();
Enumeration<URL> en = bundle.findEntries(dir, "*", true);
while (en.hasMoreElements()) {
URL url = en.nextElement();
String pathFromBase = url.getPath().substring(dir.length()+1);
String toFileName = destination + pathFromBase;
File toFile = new File(toFileName);
if (pathFromBase.lastIndexOf('/') == pathFromBase.length() - 1) {
// This is a directory - create it and recurse
if (!toFile.mkdir()) {
throw new IOException("bundleCopy: " + "directory Creation Failed: " + toFileName);
}
} else {
// This is a file - copy it
FileCopy.coreStreamCopy(url.openStream(), toFile);
}
}
}
答案 1 :(得分:0)
您可以尝试使用new File(FileLocator.resolve(url).toUri())
之类的东西将特定于Eclipse的URL转换为使用本机Java协议的URL。