java配置文件路径

java配置文件路径写法

java程序中经常使用配置文件,将程序打成jar包后,配置文件的路径该如何设置,放于jar包内和外部时,代码如何写,在此做个记录。

测试代码

		System.out.println(123);

		System.out.println("user.dir:" + System.getProperty("user.dir"));
		System.out.println("user.home:" + System.getProperty("user.home"));
		
		//InputStream in = MainApp.class.getClassLoader().getResourceAsStream("config/config.ini");
		String protectionDomain = MainApp.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		System.out.println("protectionDomain:" + protectionDomain);
		
		String path = System.getProperty("java.class.path");
		System.out.println("java.class.path:" + path);
		
		int firstIndex = path.lastIndexOf(System.getProperty("path.separator"))+1 ;
		int lastIndex = path.lastIndexOf(File.separator) +1; 
		path = path.substring(firstIndex, lastIndex); 
		System.out.println("path:" + path);
				
		System.out.println(321);

eclipse执行结果

![eclipse执行结果](https://img-blog.csdnimg.cn/2在这里插入图片描述

jar包不同路径下执行结果

jar包不同路径下执行结果

由此可见,使用user.dir设置配置文件路径并不是一个很好的解决办法,更好的应当选用protectionDomain,在程序和jar外部都可以方便使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

songhuageini

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值