gpt4 book ai didi

java - 获取给定类文件的目录路径

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:18:49 25 4
gpt4 key购买 nike

我遇到的代码试图从类本身的 .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 中做这样的事情.

不过,我想知道是否有一些通用的好方法来获取给定 .class 文件所在目录的路径?我想您可以像这样从 .class 文件本身的路径中获取它:

new File(this.getClass().getResource("MyClass.class").getPath()).getParent()

...但这是唯一/最干净的方法吗?

编辑:为澄清起见,假设我们知道这是在以这样一种方式部署的应用程序中使用的,即 MyClass.class 将始终从 .class 文件中读取磁盘,资源将位于同一目录中。

最佳答案

我知道这个话题很旧,但它是 Google 搜索中的最高结果,而且这里没有对我来说满意的答案。这是我写的一些代码,对我来说非常有用。当然,需要注意的是它可能不是从磁盘加载的,但它说明了这一点,并在这种情况下返回 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);
}
}

关于java - 获取给定类文件的目录路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1188400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com