spring boot 读取resources下文件 和 打成jar 读取jar包中配置文件

在Spring Boot项目被打成jar包运行时,通过传统路径方式无法正确读取配置文件,会出现类似file:/D:/xxx/xxx.jar!/BOOT-INF/classes!/xx.xx的错误。解决方案是利用Class.getResourceAsStream()方法,通过流的方式读取classpath下的配置文件,如key.txt,从而避免路径错误问题。

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

问题:

        由于使用spring boot + maven 管理项目,所以会把项目打成jar包来进行运行。在不打成jar的情况下,正常情况一般都是读取绝对路径来进行获取配置文件路径。

String url = SensitiveWordInit.class.getResource("/").getFile();
File file = ResourceUtils.getFile("classpath:key.txt");

以上两种方法来获取。但是当项目打包成jar 包时,通过路径获取会出现file:/D:/xxx/xxx.jar!/BOOT-INF/classes!/xx.xx 的错误。

解决办法:

        当项目打成jar包时,还需要读取配置文件。需要通过流的形式来进行读取。方法如下

private Set<String> readWordFile() throws Exception{
		Set<String> set = null;
//		File file = ResourceUtils.getFile("classpath:key.txt");
//		System.out.println(file.toString());
//		String url = SensitiveWordInit.class.getResource("/").getFile();
//		System.out.println("readSensitiveWordFile" + url);
//		File file = new File(url+"key.txt");    //读取文件
		InputStream inputStream = SensitiveWordInit.class.getResourceAsStream("/key.txt");
		InputStreamReader read = new InputStreamReader(inputStream,ENCODING);
		try {
				set = new HashSet<>();
				BufferedReader bufferedReader = new BufferedReader(read);
				String txt ;
				while((txt = bufferedReader.readLine()) != null){    //读取文件,将文件内容放入到set中
					set.add(txt);
				}
		} catch (Exception e) {
			throw e;
		}finally{
			read.close();     //关闭文件流
		}
		return set;
	}

通过

InputStream inputStream = SensitiveWordInit.class.getResourceAsStream("/key.txt");

来获取classpath 下的key.txt 来进行读取。这样就避免了路径的错误问题。

以上就是读取jar包中的配置文件问题解决办法。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值