ClassLoader获取指定路径下的文件

@RestController
@RequestMapping("loder")
public class ClassLoaderContrpller {
    public static void main(String[] args) {
        ClassLoaderContrpller loaderContrpller = new ClassLoaderContrpller();
        //1.通过当前线程获取ClassLoader
        ClassLoader classLoader1 = Thread.currentThread().getContextClassLoader();

        //2.通过类获取ClassLoader
        ClassLoader classLoader2 = ClassLoaderContrpller.class.getClassLoader();

        //sun.misc.Launcher$AppClassLoader@18b4aac2=sun.misc.Launcher$AppClassLoader@18b4aac2 true
        System.out.println(classLoader2==classLoader1);

        //获取ClassPath的路径
        //file:/C:/Users/Administrator/Desktop/wake/springboot-redis/target/classes/
        URL resource = loaderContrpller.getClass().getClassLoader().getResource("");

        //获取ClassPath根下的application.properties文件
        //file:/C:/Users/Administrator/Desktop/wake/springboot-redis/target/classes/application.properties
        URL resource1 = loaderContrpller.getClass().getClassLoader().getResource("application.properties");

        //获取ClassPath根下的application.properties文件流
        //java.io.BufferedInputStream@32a1bec0
        InputStream asStream = loaderContrpller.getClass().getClassLoader().getResourceAsStream("application.properties");

        //获取ClassPath根下properties包中的field.properties
        //file:/C:/Users/Administrator/Desktop/wake/springboot-redis/target/classes/properties/field.properties
        URL resource2 = loaderContrpller.getClass().getClassLoader().getResource("properties/field.properties");

        //通过类的类文件获取路径
        //file:/C:/Users/Administrator/Desktop/wake/springboot-redis/target/classes/
        URL resource3 = loaderContrpller.getClass().getResource("/");
        
        //通过类的类文件获取对应路径的对应文件流
        //java.io.BufferedInputStream@22927a81
        InputStream resourceAsStream = loaderContrpller.getClass().getResourceAsStream("/application.properties");
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值