关于classpath的理解和使用

本文详细解释了ClassPath的概念及其重要性,并介绍了如何利用Java的ClassLoader类来加载ClassPath路径下的资源文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是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);
}














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值