In Java, you can load all kinds of resources using the same API but with different URL protocols:

file:///tmp.txt
http://127.0.0.1:8080/a.properties
jar:http://www.foo.com/bar/baz.jar!/COM/foo/Quux.class

This nicely decouples the actual loading of the resource from the application that needs the resource, and since a URL is just a String, resource loading is also very easily configurable.

Is there a protocol to load resources using the current classloader? This is similar to the Jar protocol, except that I do not need to know which jar file or class folder the resource is coming from.

I can do that using Class.getResourceAsStream("a.xml"), of course, but that would require me to use a different API, and hence changes to existing code. I want to be able to use this in all places where I can specify a URL for the resource already, by just updating a property file.

Intro and basic Implementation

First up, you're going to need at least a URLStreamHandler. This will actually open the connection to a given URL. Notice that this is simply called Handler; this allows you to specify java -Djava.protocol.handler.pkgs=org.my.protocols and it will automatically be picked up, using the "simple" package name as the supported protocol (in this case "classpath").

Usage

new URL("classpath:org/my/package/resource.extension").openConnection();

Code

package org.my.protocols.classpath;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler; /** A {@link URLStreamHandler} that handles resources on the classpath. */
public class Handler extends URLStreamHandler {
/** The classloader to find resources from. */
private final ClassLoader classLoader; public Handler() {
this.classLoader = getClass().getClassLoader();
} public Handler(ClassLoader classLoader) {
this.classLoader = classLoader;
} @Override
protected URLConnection openConnection(URL u) throws IOException {
final URL resourceUrl = classLoader.getResource(u.getPath());
return resourceUrl.openConnection();
}
}

Launch issues

If you're anything like me, you don't want to rely on a property being set in the launch to get you somewhere (in my case, I like to keep my options open like Java WebStart - which is why I need all this).

Workarounds/Enhancements

Manual code Handler specification

If you control the code, you can do

new URL(null, "classpath:some/package/resource.extension", new org.my.protocols.classpath.Handler(ClassLoader.getSystemClassLoader()))

and this will use your handler to open the connection.

But again, this is less than satisfactory, as you don't need a URL to do this - you want to do this because some lib you can't (or don't want to) control wants urls...

JVM Handler registration

The ultimate option is to register a URLStreamHandlerFactory that will handle all urls across the jvm:

package my.org.url;

import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.HashMap;
import java.util.Map; class ConfigurableStreamHandlerFactory implements URLStreamHandlerFactory {
private final Map<String, URLStreamHandler> protocolHandlers; public ConfigurableStreamHandlerFactory(String protocol, URLStreamHandler urlHandler) {
protocolHandlers = new HashMap<String, URLStreamHandler>();
addHandler(protocol, urlHandler);
} public void addHandler(String protocol, URLStreamHandler urlHandler) {
protocolHandlers.put(protocol, urlHandler);
} public URLStreamHandler createURLStreamHandler(String protocol) {
return protocolHandlers.get(protocol);
}
}

To register the handler, call URL.setURLStreamHandlerFactory() with your configured factory. Then do new URL("classpath:org/my/package/resource.extension") like the first example and away you go.

JVM Handler Registration Issue

Note that this method may only be called once per JVM, and note well that Tomcat will use this method to register a JNDI handler (AFAIK). Try Jetty (I will be); at worst, you can use the method first and then it has to work around you!

License

I release this to the public domain, and ask that if you wish to modify that you start a OSS project somewhere and comment here with the details. A better implementation would be to have a URLStreamHandlerFactory that uses ThreadLocals to store URLStreamHandlers for each Thread.currentThread().getContextClassLoader(). I'll even give you my modifications and test classes.

URL to load resources from the classpath in Java的更多相关文章

  1. Load resources from classpath in Java--reference

    In general classpath is the path where JVM can find .class files and resources of your application a ...

  2. The SSL certificate used to load resources from xxx will be distrusted in M70.

    今天在浏览网站的时候遇到如下报警信息: The SSL certificate used to load resources from https://xxx.com will be distrust ...

  3. Java 实例 - 如何执行指定class文件目录(classpath) Java 实例 J

    Java 实例 - 如何执行指定class文件目录(classpath)  Java 实例 如果我们 Java 编译后的class文件不在当前目录,我们可以使用 -classpath 来指定class ...

  4. 环境变量/path/classpath/JAVA_HOME/JAVA环境变量配置

    环境变量 环境变量是在操作系统中一个具有特定名字的对象,它包含了一个或者多个应用程序所将使用到的信息.例如Windows和DOS操作系统中的path环境变量,当要求系统运行一个程序而没有告诉它程序所在 ...

  5. path 与classpath针对JAVA来说

    Path 路径,是java编译时需要调用的程序(如java,javac等)所在的地方CLASSPATH 类的路径,在编译运行java程序时,如果有调用到其他类的时候,在classpath中寻找需要的类 ...

  6. 使用任意的输入流(InputStream)实例,包括字符串形式的文件路径或者 file:// 的 URL 形式的文件路径来配置

    mybatis – MyBatis 3 | 入门 http://www.mybatis.org/mybatis-3/zh/getting-started.html 从 XML 中构建 SqlSessi ...

  7. How to load a local .CSS file & JavaScript resources using iPhone UIWebView Class

    This post will cover the basic setup and creation of an application with web content for iPhone that ...

  8. springboot-项目获取resources下文件碰到的问题(classPath下找不到文件和文件名乱码)

    项目是spring-boot + spring-cloud 并使用maven 管理依赖.在springboot+maven项目下怎么读取resources下的文件实现文件下载? 怎么获取resourc ...

  9. 一个编译可执行jar包 jar包中不包含resources下config.properties且可以读到config.properties文件且classpath中有当前路径的pom

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

随机推荐

  1. 蚂蚁金服“定损宝”现身AI顶级会议NeurIPS

    小蚂蚁说: 长期以来,车险定损(通过现场拍摄定损照片确定车辆损失,以作为保险公司理赔的依据)是车险理赔中最为重要的操作环节.以往传统保险公司的车险处理流程,一般为报案.现场查勘.提交理赔材料.审核.最 ...

  2. 使用JS语句,利用for循环的方法创建表格的两种方法

    首先去layui官网下载教程示例,在项目中加载layui.css,layui.js,JQuery.js 第一种: 将jsp语句写成字符串的形式,使用document.write()方式输出: 代码如下 ...

  3. synchronized和volatile

    迄今为止,看到的最清楚的一篇: https://zhuanlan.zhihu.com/p/29866981 volatile https://zhuanlan.zhihu.com/p/34362413

  4. 堆排序 java实现

    import java.util.Arrays; /* * 思路: * 1.方法adjustDown:对于一个数组a[],针对第i个数进行向下(直到len-1)调整,使得该位置成为大顶堆 * 2.方法 ...

  5. Windows下的Python 3.6.1的下载与安装(适合32bits和64bits)(图文详解)

    不多说,直接上干货! 为什么,这么简单的一个python,我还要特意来写一篇博客呢? 是因为留念下,在使用了Anaconda2和Anaconda3的基础上,现在需安装python3.6.0来做数据分析 ...

  6. TextView显示内容不全

    今天开发遇到一个问题,发现TextView显示不全,很纳闷,看图: 正常情况应该是这个样子的: 造成这种情况的原因是: TextView被快速并且多次的设置内容值造成的. 我的场景: 我点击全选按钮, ...

  7. PCA分析和因子分析

    #由此说明使用prcomp函数时,必须使用标准化过的原始数据.如果使用没有标准化的raw数据(不是相关系数矩阵或者协方差矩阵),必须将参数scale. = T <result>$sdev ...

  8. js正则表达式的积累

    验证数字:^[0-9]*$ 验证n位的数字:^\d{n}$ 验证至少n位数字:^\d{n,}$ 验证m-n位的数字:^\d{m,n}$ 验证零和非零开头的数字:^(0|[1-9][0-9]*)$ 验证 ...

  9. css图片的全屏显示代码-css3

    <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" ...

  10. 纯CSS方块转化梯形动画

    http://jasonning92.github.io/JasonsBlog/pages/%E7%BA%AFCSS%E6%96%B9%E5%9D%97%E8%BD%AC%E5%8C%96%E6%A2 ...