Java读取classpath下文件的两种方式

代码实例

getResource

    // 获取URL资源路径进行读取
    private static void readClassPathByUrl()  throws Exception{
        URL url = App.class.getClassLoader().getResource("config.properties");
        System.out.println(url.getPath());
        FileInputStream inputStream = new FileInputStream(url.getPath());
        Properties properties = new Properties();
        properties.load(inputStream);
        Object username = properties.get("username");
        System.out.println(username);
        inputStream.close();
    }

getResourceByStream

    // 获取jar包classpath的文件流
    private static void readClassPathByStream() throws Exception{
        InputStream stream = App.class.getClassLoader().getResourceAsStream("config.properties");
        Properties properties = new Properties();
        properties.load(stream);
        System.out.println(properties.get("username"));
        stream.close();
    }

调用方法与待读取文件

image.png

代码执行与调试

本地运行

本地运行,两种方式都可以读取到classpath下面的文件

部署jar包运行

image.png

image.png

总结

  1. 使用Jar包进行调用getResource方法报错了,并且提示原因为找不到文件,可以仔细看运行时我已经把路径打印出来了,路径是一个绝对路径,并且这个路径明显是错误的,jar包不是一个文件夹,而是一个文件。
  2. 为啥使用idea本地运行没有报错,因为使用本地运行可以通过路径找到文件,所以没报错

image.png

  1. 读取classpath下的文件是Java开发的常见需求,例如读取excel模板,读取额外的配置文件,在开发过程中推荐使用 getResourceByStream方法,不然打jar包部署调用时就会报错,不管windows系统还是Linux系统都一样
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值