打包jar读取配置文件

一、根据System getProperties 中user.dir的值查找。

private static Properties pros = new Properties();

private static final String FILENAME = "my.properties";
//加载属性文件
static {
try {
String path = System.getProperty("user.dir") + File.separator + FILENAME;
File file = new File(path);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
pros.load(in);
in.close();
} else {

String filePath = System.getProperty("user.dir");
log.error(path);
log.error("=========>错误:系统未发现配置文件"+FILENAME+"=========");
log.error("配置文件应该放在 "+filePath+"下");
log.error("=========>该文件模板可在jar中获取====================");
}
} catch (Exception e) {
log.error("==================>load configuration error", e);
}
}

特点:user.dir的值取决于执行jar包时所在目录下,若执行jar包不在jar包所在的路径则存在找不到配置文件,未打jar包时,在eclipse中执行此程序则user.dir指的是src同级的路径

二、

private static Properties pros = new Properties();

try {
InputStream in = PropertyUtil.class.getClassLoader().getResourceAsStream("conf/my.properties");
pros.load(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}

三、

private static Properties pros = new Properties();

try {
       URL url = PropertyUtil.class.getProtectionDomain().getCodeSource().getLocation();
       String filePath = null;
       try {
           filePath = URLDecoder.decode(url.getPath(), "utf-8");
       } catch (Exception e) {
           e.printStackTrace();
       }
       if (filePath.endsWith(".jar"))
           filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
       File file = new File(filePath);
       filePath = file.getAbsolutePath();
file = new File(filePath+File.separator+"my.properties");
if (file.exists()) {// 如果为设置的话系统会读取默认配置
FileInputStream in = new FileInputStream(file);
pros.load(in);
in.close();
} else {
System.out.println("=========错误:系统未发现配置文件========");
System.out.println("在 "+filePath+"下未发现配置文件");
System.out.println("=========该文件模板可在jar中获取========");
}

} catch (Exception e) {
e.printStackTrace();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值