Java 快捷读取CLASSPATH下的资源文件

在JVM中查找classpath下的资源文件,使用Class.getResource()方法会方便些.

 

     * @param  name name of the desired resource
     */
    public java.net.URL getResource(String name) {
        name = resolveName(name);
        ClassLoader cl = getClassLoader0();
        if (cl==null) {
            // A system class.
            return ClassLoader.getSystemResource(name);
        }
        return cl.getResource(name);
    }

 

测试代码:

 

/**
 * @author LionBule
 */
public class Test {
	public static void main(String[] args) throws InterruptedException {
	    // classpath:/rules/HelloWorld.drl
	    Test t = new Test();
	    String tfilePath = t.getClass().getResource("/rules/HelloWorld.drl").getPath();
	    System.out.println("tfilePath = \t"+tfilePath);
	    String tfile = t.getClass().getResource("/rules/HelloWorld.drl").getFile();
	    System.out.println("tfile = \t"+tfile);
	}
}

执行结果:

tfilePath = 	/D:/codes/lionbule-java-test/target/classes/rules/HelloWorld.drl
tfile = 	/D:/codes/lionbule-java-test/target/classes/rules/HelloWorld.drl
 

java.net.URL

URL.path 和 URL.file的区别,官方说明如下:

 

    /**
     * The specified file name on that host. <code>file</code> is
     * defined as <code>path[?query]</code>
     * @serial
     */
    private String file;
    /**
     * The path part of this URL.
     */
    private transient String path;

你可能感兴趣的:(classpath)