访问jar包外部properties文件

本文介绍了一种从jar外部获取配置信息的方法,包括适用于Windows和Linux系统的实现方式。通过使用Properties类,可以轻松地加载并读取指定路径下的配置文件。

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

    /**********************************本方法只适用于windows操作系统********************************
     * 从jar外部获取配置信息
     * @param path
     *            文件路径及文件名 格式为 aa/bb/path.properties
     * @param name
     *            需要获取的属性名
     * @return
     */
    public static String urlPort(String path, String name) {
        try {
            Properties prop = new Properties();
            InputStream in = new BufferedInputStream(new FileInputStream("../" + path));
            prop.load(in);
            String property2 = prop.getProperty("BDTJ_TIMER");
            System.out.println(property2);
            // Enumeration<?> propertyNames = prop.propertyNames();
            // Object object = prop.get("");
            // System.out.println(object.toString());
            // while(propertyNames.hasMoreElements()) {
            // String key = (String) propertyNames.nextElement();
            // String property = prop.getProperty(key);
            // System.out.println(key+"   "+property);
            // }
            return property2;
        } catch (Exception e) {
        }
        return null;
    }
/********************************此方法适用于windows和lunix********************************
public class PathTest {
    public static void main(String[] args) throws Exception {
//        new PathTest().getClass().getProtectionDomain().getCodeSource().getLocation();
        System.out.println(readPort("JG_TIMER"));
    }
    /**
     * 从jar外部获取配置信息
     * @param path
     *            文件路径及文件名 格式为 /aa/bb/path.properties (根目录为jar所在目录)
     * @param name
     *            需要获取的属性名
     * @return
     */
    public static String readPort(String name) {
        String property = System.getProperty("user.dir");
        try {
            Properties prop = new Properties();
            InputStream in = new BufferedInputStream(new FileInputStream(property+"port.properties"));
            prop.load(in);
            String value = prop.getProperty(name);
            if (null==value || value.equals("")) {
                System.out.println("配置文件中不存在该属性");
            }
            return value;
        } catch (Exception e) {
            System.out.println("获取配置文件出错,请检查路径");
            e.printStackTrace();
        }
        return null;
    }
}  

/*************************************第三种方式*******************************************
全部为 jar路径以及jar包名称:
URL location = new ReadPortUtil().getClass().getProtectionDomain().getCodeSource().getLocation();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值