关于classpath的理解和使用
来源:互联网 发布:陈乔恩长相知乎 编辑:程序博客网 时间:2024/05/22 01:45
什么是classpath路径?
所谓的classpath指的就是编译后的class文件所在的目录,即为classpath路径。
上图是一个eclipse项目工程的结构,target目录是编译输出目录,打开target目录结构如下:
其中classes目录即为classpath路径,对应于项目源码中的resources目录。
如何加载classpath路径下的资源?
java中提供了ClassLoader类用于加载classpath下的资源。ClassLoader对象中的getResourceAsStream(String name)可以将资源以流的形式加载进内存中。
ClassLoader的使用
ClassLoader对象的创建方式
方式一:使用ClassLoader类的静态方法getSystemClassLoader()获取。
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
方式二:通过当前的Thread线程对象获取。
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
方式三:使用Class字节码对象的getClassLoader()获取。
public class A {public void getClassLoader() {ClassLoader classLoader = this.getClass().getClassLoader();}}
ClassLoader读取资源
/** * 读取classpath下的资源文件 */@Testpublic void test1() throws Exception {ClassLoader classLoader = Thread.currentThread().getContextClassLoader();InputStream in = classLoader.getResourceAsStream("jdbc.properties");Properties prop = new Properties();prop.load(in);prop.entrySet().forEach(System.out::println);}
/** * 读取当前类路径下的资源文件 */@Testpublic void test2() throws Exception {// 获取当前类在classpath下的路径String packageName = this.getClass().getPackage().getName().replaceAll("\\.", "/");ClassLoader loader = this.getClass().getClassLoader();InputStream in = loader.getResourceAsStream(packageName + "/Jdbc.properties");Properties prop = new Properties();prop.load(in);prop.entrySet().forEach(System.out::println);}
阅读全文