我有一个项目,在这个项目中,我针对许多XSD生成了许多代码。为了使事情分开,每一组XSD都捆绑在一个项目中。我有多个项目将在资源中看到XSD并根据它们生成代码。
我的问题是,当我试图访问存储在JAR文件中的XSD时,我无法从特定的JAR获取访问XSD的代码。相反,它将访问与条件匹配的第一个XSD,而不管JAR是什么。
这里是我用来列出资源的代码,所有jar都具有相同的结构,这意味着xsd总是存储在jar文件根目录下的xsd文件夹中。下面的代码列出了文件夹中的XSD。
URL dirURL = clazz.getClassLoader().getResource(path);
System.out.println(dirURL.toURI());
if (dirURL != null && dirURL.getProtocol().equals("file")) {
/* A file path: easy enough */
System.out.println(dirURL.toURI());
return new File(dirURL.toURI()).list();
}
if (dirURL == null) {
/*
* In case of a jar file, we can't actually find a directory.
* Have to assume the same jar as clazz.
*/
String me = clazz.getName().replace(".", "/") + ".class";
dirURL = clazz.getClassLoader().getResource(me);
System.out.println(dirURL.toURI());
System.out.println(me);
}
if (dirURL.getProtocol().equals("jar")) {
/* A JAR path */
String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
System.out.println(jarPath);
JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory
String name = null;
while (entries.hasMoreElements()) {
name = entries.nextElement().getName();
if (name.startsWith(path)) { //filter according to the path
String entry = name.substring(path.length());
int checkSubdir = entry.indexOf("/");
if (checkSubdir >= 0) {
// if it is a subdirectory, we just return the directory name
entry = entry.substring(0, checkSubdir);
}
result.add(entry);
}
}
return result.toArray(new String[result.size()]);