java – 如何访问jar中的资源,它可以存在于多个jar中
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 如何访问jar中的资源,它可以存在于多个jar中,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2397字,纯文字阅读大概需要4分钟。
内容图文
![java – 如何访问jar中的资源,它可以存在于多个jar中](/upload/InfoBanner/zyjiaocheng/783/a9a65b8fb1b843688e1d103c0748266c.jpg)
我有一个项目,我可以针对许多XSD生成大量代码.为了使事物分离,每组XSD在项目中捆绑在一起.我有多个项目,它将在资源中看到XSD并生成针对它们的代码.
我的问题是当我尝试访问存储在jar文件中的XSD时,我无法从一个特定的jar中获取访问XSD的代码.相反,无论jar如何,它都将访问与标准匹配的第一个XSD.
这是我用来列出资源的代码,所有的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()]);
解决方法:
我通常会规定将资源目录添加到每个JAR中,并使用对其下保存的JAR唯一的资源.例如(在Maven结构中)
module1/src/main/resources/module1/example.xsd
module2/src/main/resources/module2/example.xsd
然后使用引用XSD
InputStream module1XSD= SomeClass.class.getResourceAsStream("/module1/example.xsd");
InputStream module2XSD= SomeClass.class.getResourceAsStream("/module2/example.xsd");
只要module1和module2的JAR放在包含SomeClass的应用程序的类路径上.
Spring语境将引用这些作为
classpath:module1/example.xsd,
classpath:module2/example.xsd
这意味着您必须能够在您生成的JAR中移动XSD的位置.甚至可能通过构建脚本重新生成它们.
内容总结
以上是互联网集市为您收集整理的java – 如何访问jar中的资源,它可以存在于多个jar中全部内容,希望文章能够帮你解决java – 如何访问jar中的资源,它可以存在于多个jar中所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。