什么是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下的资源文件
*/
@Test
public 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);
}
/**
* 读取当前类路径下的资源文件
*/
@Test
public 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);
}