获取给定类文件目录的路径 [英] Getting the path to the directory of a given class file

查看:62
本文介绍了获取给定类文件目录的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了试图从同一目录中读取某些配置文件的代码,其中该类本身的.class文件为:

I was confronted with code which tries to read some configuration files from the same directory where the .class file for the class itself is:

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.

Apparently this works in some cases (when running the code inside Resin, perhaps), but for me, running Tomcat, it simply fails with NPE, because getClass().getResource(".") returns null.

一位同事建议创建另一个配置文件,其中包含所有".xml"配置文件的列表(确实可以在这里使用,因为它保持非常静态),并且您不应该真正尝试在Java中做类似的事情.

A colleague suggested creating another config file containing a list of all the ".xml" config files (which indeed would work here as it stays quite static), and that you shouldn't really try to do something like this in Java.

仍然,我想知道是否存在一些通用方法,该通用方法可以获取给定.class文件所在目录的路径?我想您可以从.class文件本身的路径中获取它,如下所示:

Still, I'm wondering if there is some nice way, which works universally, for getting the path to the directory where a given .class file is located? I guess you could get it from the path of the .class file itself like this:

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

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

... but is this the only / cleanest way?

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

Edit: To clarify, assume we know this is used in an application deployed in such a way that MyClass.class will always be read from a .class file on disk, and the resources will be there in that same directory.

推荐答案

我知道这个线程很旧,但是它是Google搜索的最高结果,对我而言,这里没有令人满意的答案.这是我写的一些代码,对我来说非常有用.当然,需要警告的是它可能尚未从磁盘加载,但它说明了这一点,并且在这种情况下返回null.这对于查找容器"(即类的根位置,无论是jar还是文件夹)都很好.这可能无法直接满足您的需求.如果没有,请随意删除您需要的代码部分.

I know this thread is old, but it's the top result in Google searches, and there were no satisfactory answers on here, for me. Here's some code I wrote, which works great for me. Of course there's the caveat that it may not have been loaded from disk, but it accounts for that, and returns null in that case. This works fine for finding the "container," that is, the root location of a class, be it a jar, or a folder. This may not suit your needs directly. If not, feel free to rip out the portions of the code that you do need.

/**
 * 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);
    }
}

这篇关于获取给定类文件目录的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆