解决java打包成jar包访问文件的绝对路径报错问题

看到有小伙伴提问java打包成jar包访问文件的绝对路径报错问题。
这里给出一个解决方案:
	解释:打包成jar包后,直接访问文件绝对路径是找不到文件的,会抛出FileNotFoundException。
	必须以IO流的方式访问文件。接下来看例子,直接上代码!
    public static void main(String[] args) {
        Properties prop = new Properties();
        try {
//            File file = new FileSystemResource("src/main/resources/domian.properties").getFile();
            prop.load(new ClassPathResource("/domian.properties").getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        Enumeration<Object> keys = prop.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement().toString();
            String value = prop.getProperty(key);
            System.out.println(value);
        }
    }

文件位置:

在这里插入图片描述

如果有编码问题,使用这段代码设置编码

Properties prop = new Properties();
        try {
//            File file = new FileSystemResource("src/main/resources/domian.properties").getFile();
            prop.load(new InputStreamReader(new ClassPathResource("/prop.properties").getInputStream(), "GBK"));
        } catch (IOException e) {
            e.printStackTrace();
        }

其中的ClassPathResource类需要导入jar包:

		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值