简体   繁体   English

如何使用类加载器作为文件加载资源?

[英]How do I load resource using Class Loader as File?

I want to open files using the class loader. 我想使用类加载器打开文件。 However I always get a FileNotFoundException. 但是我总是得到一个FileNotFoundException。 How do I create a new File using the URL? 如何使用URL创建新文件? I don't want to open it as a stream just as a file. 我不想像文件一样打开它作为流。

URL url = VersionUpdater.class.getResource("xslt/screen/foo");
File f = ...

To convert a file://... URL to java.io.File , you'll have to combine both url.getPath() and url.toURI() for a safe solution: 要将file://... URL转换为java.io.File ,您必须将url.getPath()url.toURI()成一个安全的解决方案:

File f;
try {
    f = new File(url.toURI());
} catch(URISyntaxException e) {
    f = new File(url.getPath());
}

Full explanations in this blog post . 博文中的完整解释。

I'm just thinking: What if foo is in a jar? 我只是想:如果foo在罐子里怎么办? Then you couldn't construct a File. 然后你无法构造一个文件。

It should be possible to make it work, if foo is really in a (local) classpath directory - but you know, it will fail, if someone packages it up in a jar, or loads it via the network... 应该可以使它工作,如果foo真的在(本地)类路径目录中 - 但是你知道,它会失败,如果有人将它打包在jar中,或者通过网络加载它...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM