通过Java代码获取jar路径以及优雅的配置文件

lyzx_hero

一般在服务器上部署项目时是一个jar包  旁边放置一个配置文件的文件夹conf,如下图所示 ,  在IDEA中结构如上所示

 

 

那么怎么做到在IDEA中写的代码能加载配置文件,同时放到服务器上不用修改代码呢?

下面介绍两种方式

package com.lyzx.test;

import java.io.File;

public class T3 {
    public static void main(String[] args){
        String domain_path = T3.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String file_path = new File("").getAbsolutePath();

        System.out.println("通过domain方式获取的jar包的绝对路径(包含jar包的名字)="+domain_path);
        System.out.println("通过file相对路径的方式获取的绝对路径(不包含jar包的名字)="+file_path);

        //在服务器端时,domain方式获取的路径带有jar包的名字,此时需要做处理
        if(domain_path.endsWith(".jar")){
            domain_path = domain_path.substring(0,domain_path.lastIndexOf(File.separator));
            System.out.println("domain方式服务器端处理后(去掉jar包名)的绝对路径=>"+domain_path);
        }

        /**
         * 下面是三种优雅的加载配置文件的方式
         * 个人推荐第一种
         */
        File file0 = new File("conf" + File.separator + "log4j.properties");
        System.out.println("通过file相对路径的方式加载配置文件::"+file0.getAbsolutePath()+"            "+file0.exists());


        File file1 = new File(file_path + File.separator + "conf" + File.separator + "log4j.properties");
        System.out.println("通过file绝对路径的方式加载配置文件::"+file1.getAbsolutePath()+"            "+file1.exists());

        //通过这种方式读取的是编译后的位置的配置文件,在IDEA中需要在 target/classes 下放置配置文件的文件夹以及文件
        File file2 = new File(domain_path + File.separator + "conf" + File.separator + "log4j.properties");
        System.out.println("通过domain的绝对路径加载配置文件::"+file2.getAbsolutePath()+"        "+file2.exists());
    }
}

本地测试结果如下:

服务器测试结果如下:

ok ,完美解决问题!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值