欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 中Ini格式配置文件读取

程序员文章站 2024-01-01 21:05:40
java中Ini格式配置文件读取创建 config.ini配置文件读取配置文件完整代码package com.kingyea.boot.modules.data.config;import org.ini4j.Config;import org.ini4j.Ini;import org.ini4j.Profile;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.BufferedRead...

java中Ini格式配置文件读取

创建 config.ini配置文件
java 中Ini格式配置文件读取

读取配置文件完整代码

package com.kingyea.boot.modules.data.config;

import org.ini4j.Config;
import org.ini4j.Ini;
import org.ini4j.Profile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class ConfigIni {

    private static final Logger LOG = LoggerFactory.getLogger(ConfigIni.class);
    public static Ini ini ;

    public ConfigIni() {
    }

    public static Profile.Section getSection(String sectionName) {
        return (Profile.Section)ini.get(sectionName);
    }

    public static String getProperty(String name) {
        return getProperty("access", name);
    }

    public static String getProperty(String sectionName, String name) {
        return ini.get(sectionName, name);
    }

    public static String getEsProperty(String name) {
        String val = ini.get("es", name);
        if(name.equals("separation")){
            val = " " + val + " ";
        }
        return val;
    }

    public static String getMysqlProperty(String name) {
        String val = ini.get("mysql", name);
        return val;
    }

    static {
        try {
            Config cfg = new Config();
            cfg.setMultiSection(true);
            ini = new Ini();
            ini.setConfig(cfg);
            URL url = ConfigIni.class.getClassLoader().getResource("config.ini");
            if (url == null) {
                throw new RuntimeException("未找到config.ini,请检查classpath");
            } else {
                URLConnection urlConnection = url.openConnection();
                InputStream inputStream = urlConnection.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
                if (in == null) {
                    throw new RuntimeException("未找到config.ini,请检查classpath");
                } else {
                    ini.load(in);
                }
            }
        } catch (Exception var5) {
            throw new RuntimeException("加载config.ini失败", var5);
        }
    }

    public static void main(String[] args) {
        String property = getProperty("ES", "cols");
        System.out.println(property);
    }

}

本文地址:https://blog.csdn.net/weixin_40335533/article/details/111991843

上一篇:

下一篇: