【Java】读取配置文件

Friday, August 18, 2023
本文共264字
1分钟阅读时长

⚠️本文是作者P3troL1er原创,首发于https://peterliuzhi.top/posts/java%E8%AF%BB%E5%8F%96%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6/。商业转载请联系作者获得授权,非商业转载请注明出处!

Fame usually comes to those who are thinking about something else. — Oliver Wendell Holmes Jr.

引入

可以使用java.util.Properties来读取一个普通的配置文件

配置文件示例:

fromAddress: "xxx@163.com"
Password : "xxx"
toAddress: "xxx@qq.com"
templateFileAddress: "xxx\\xxx"

代码

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;

public class ConfigReader {
    private HashMap<String, String> configMap = new HashMap<>();
    private String configFileName = "";
    public ConfigReader(){
    }
    public ConfigReader(String configFileName){
        this.readConfig(configFileName);
    }
    public void readConfig(String configFileName) {
        this.configFileName = configFileName;
        Properties properties = new Properties();
        try {
            FileInputStream fileInputStream = new FileInputStream(configFileName);
            properties.load(fileInputStream);
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 遍历配置项并存储到哈希表中
        for (String key : properties.stringPropertyNames()) {
            String value = properties.getProperty(key);
            configMap.put(key, value);
        }

        // 打印配置项值
        new LogWriter().info(configMap);
    }
    public String getConfigItem(String item){
        return this.configMap.get(item);
    }
    public String[] getConfigItem(String... item){
        int itemLen = item.length;
        String[] ret = new String[itemLen];
        for (int i = 0; i < itemLen; ++i){
            ret[i] = this.configMap.get(item[i]);
        }
        return ret;
    }
    public String[] getWholeConfig(){
        int len = this.configMap.size();
        String[] ret = new String[len];
        String[] configKeys = this.configMap.keySet().toArray(new String[0]);
        String[] configVals = this.configMap.values().toArray(new String[0]);
        for (int i = 0; i < len; i++) {
            ret[i] = configKeys[i] + "=" + configVals[i];
        }
        return ret;
    }
    public String[] getAllVals(){
        return this.configMap.values().toArray(new String[0]);
    }
    public String[] getAllKeys(){
        return this.configMap.keySet().toArray(new String[0]);
    }
}