Android 讀取ini文件配置項

這個是帶Section的文件讀取,ini文件放在assets目錄下

使用方法:

String titleCount = ConfigMgr.getInstance(MainActivity.this).readProperties("TestGroup", "titleCount");

ini配置:

;測試分組
[TestGroup]
;標題的個數
titleCount=4

代碼:

注意:STR_CONFIG_FILE 值的設置一定是你自己的ini文件名稱,否則會找不到文件的

package com.yejinmo.example.utils;

import android.content.Context;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Properties;

/**
 * @className: ConfigMgr
 * @author: yejinmo
 * @date: 2019/6/3 21:18
 * @Description: ini文件讀取工具類
 */
public class ConfigMgr {
    /** 配置文件 */
    private static final String STR_CONFIG_FILE = "study.ini";
    private static HashMap<String, Properties> sections = new HashMap<>();
    private static transient Properties properties;
    private static ConfigMgr sConfigMgr;
    private final Context mContext;

    private ConfigMgr(Context context) {
        mContext = context;
    }

    public static synchronized ConfigMgr getInstance(Context context) {
        if (null == sConfigMgr) {
            sConfigMgr = new ConfigMgr(context);
        }
        return sConfigMgr;
    }

    public String readProperties(String section, String key) {
        try {
            InputStream inputStream = mContext.getResources().getAssets().open(STR_CONFIG_FILE);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            read(reader);
            reader.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        Properties p = sections.get(section);

        if (p == null) {
            return null;
        }

        return p.getProperty(key);
    }

    private void read(BufferedReader reader) throws IOException {
        String line;
        while ((line = reader.readLine()) != null) {
            parseLine(line);
        }
    }

    private void parseLine(String line) {
        line = line.trim();
        if (line.matches("\\[.*\\]")) {
            String section = line.replaceFirst("\\[(.*)\\]", "$1");
            properties = new Properties();
            sections.put(section, properties);
        } else if (line.matches(".*=.*")) {
            if (properties != null) {
                int i = line.indexOf('=');
                String name = line.substring(0, i);
                String value = line.substring(i + 1);
                properties.setProperty(name, value);
            }
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章