我遇到的代码尝试从类本身的 .class 文件所在的同一目录中读取一些配置文件:
File[] configFiles = new File(
this.getClass().getResource(".").getPath()).listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".xml");
}
});
显然,这在某些情况下有效(也许在 Resin 内运行代码时),但对我来说,运行 Tomcat 时,它只是因 NPE 而失败,因为getClass().getResource(".")
回报null
.
一位同事建议创建另一个配置文件,其中包含所有“.xml”配置文件的列表(它确实可以在这里工作,因为它保持相当静态),并且您不应该真正尝试在 Java 中执行类似的操作。
不过我还是想知道是否有some通用的好方法,用于获取给定 .class 文件所在目录的路径?我想你可以从 .class 文件本身的路径中获取它,如下所示:
new File(this.getClass().getResource("MyClass.class").getPath()).getParent()
...但这是唯一/最干净的方法吗?
Edit:为了澄清,假设我们know这用于以这样的方式部署的应用程序:始终从磁盘上的 .class 文件读取 MyClass.class,并且资源将位于同一目录中。
我知道这个帖子很旧,但它是谷歌搜索的最高结果,对我来说,这里没有令人满意的答案。这是我编写的一些代码,对我来说非常有用。当然,需要注意的是它可能尚未从磁盘加载,但它解释了这一点,并在这种情况下返回 null。这对于查找“容器”(即类的根位置,无论是 jar 还是文件夹)都很有效。这可能不能直接满足您的需求。如果没有,请随意删除您确实需要的代码部分。
/**
* Returns the container url for this class. This varies based on whether or
* not the class files are in a zip/jar or not, so this method standardizes
* that. The method may return null, if the class is a dynamically generated
* class (perhaps with asm, or a proxy class)
*
* @param c The class to find the container for
* @return
*/
public static String GetClassContainer(Class c) {
if (c == null) {
throw new NullPointerException("The Class passed to this method may not be null");
}
try {
while(c.isMemberClass() || c.isAnonymousClass()){
c = c.getEnclosingClass(); //Get the actual enclosing file
}
if (c.getProtectionDomain().getCodeSource() == null) {
//This is a proxy or other dynamically generated class, and has no physical container,
//so just return null.
return null;
}
String packageRoot;
try {
//This is the full path to THIS file, but we need to get the package root.
String thisClass = c.getResource(c.getSimpleName() + ".class").toString();
packageRoot = StringUtils.replaceLast(thisClass, Pattern.quote(c.getName().replaceAll("\\.", "/") + ".class"), "");
if(packageRoot.endsWith("!/")){
packageRoot = StringUtils.replaceLast(packageRoot, "!/", "");
}
} catch (Exception e) {
//Hmm, ok, try this then
packageRoot = c.getProtectionDomain().getCodeSource().getLocation().toString();
}
packageRoot = URLDecoder.decode(packageRoot, "UTF-8");
return packageRoot;
} catch (Exception e) {
throw new RuntimeException("While interrogating " + c.getName() + ", an unexpected exception was thrown.", e);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)