给定一个类路径资源,有没有办法获取包含/包含它的java.io.File对象? [英] Given a classpath resource, is there a way to get the java.io.File object that has/contains it?

查看:194
本文介绍了给定一个类路径资源,有没有办法获取包含/包含它的java.io.File对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在类路径上有资源,我可以将它作为流加载,并且甚至还有一个URL表示。不幸的是,Url的某些实现没有正确实现lastModified。

If I have a resource on a classpath, I can both load it as stream fine, and there is even a URL representation of it. Unfortunately some implementations of the Url do not implement lastModified correctly.

我想要的是在类路径中获取某个路径,然后将其解析为一个文件它在磁盘上 - 如果它在一个jar中,那么指向jar的文件就可以了。然后我可以从File对象而不是URL获取lastModified,这将更有帮助。

What I would like is to take a path to something in the classpath, and then resolve it to a file that it is in on disk - if it in a jar, then a File pointing to the jar is fine. I can then get the lastModified from the File object instead of the URL, which will be more helpful.

推荐答案

粗略地说:

    URL url = this.getClass().getResource(myResource);
    String fileName;
    if (url.getProtocol().equals("file")) {
        fileName = url.getFile();        
    } else if (url.getProtocol().equals("jar")) {
        JarURLConnection jarUrl = (JarURLConnection) url.openConnection();
        fileName = jarUrl.getJarFile().getName();            
    } else {
        throw new IllegalArgumentException("Not a file");
    }
    File file = new File(fileName);
    long lastModified = file.lastModified();

应该做你想做的事。您将需要捕获IOException。

Should do what you want. You will need to catch IOException.

这篇关于给定一个类路径资源,有没有办法获取包含/包含它的java.io.File对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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