java中如何实现读取带有section头的ini文件

1.现有一配置文件my.ini,内容如下:

[student]
username = zhangsan
age = 20
[teacher]
username = lisi
age = 20

2.读取文件的代码如下:

import org.testng.annotations.Test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;

public class IniReader {

    protected HashMap sections = new HashMap();
    private transient String currentSecion;
    private transient Properties current;

    /**
     * 构造函数
     */
    public IniReader(String filename) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        read(reader);
        reader.close();
    }

    /**
     * 读取文件
     */
    protected void read(BufferedReader reader) throws IOException {
        String line;
        while ((line = reader.readLine()) != null) {
            parseLine(line);
        }
    }

    /**
     * 解析配置文件行
     */
    @SuppressWarnings("unchecked")
    protected void parseLine(String line) {
        line = line.trim();
        if (line.matches("\\[.*]")) {
            //取出正则表达式匹配到的内容中的第一个条件组中的内容
            currentSecion = line.replaceFirst("\\[(.*)]", "$1");//[dev]
            //创建一个Properties对象
            current = new Properties();
            //将currentSecion和current以键值对的形式存放在map集合中。
            sections.put(currentSecion, current);
        } else if (line.matches(".*=.*")) {
            if (current != null) {

                int i = line.indexOf('=');
                String name = line.substring(0, i).trim();
                String value = line.substring(i + 1).trim();
                current.setProperty(name, value);
            }
        }
    }
    /**
     * 根据提供的键获取值
     */
    public String getValue(String section, String key) {
        Properties p = (Properties) sections.get(section);
        if (p == null) {
            return null;
        }
        String value = p.getProperty(key);
        return value;
    }

}

3.测试方法如下:

import org.testng.annotations.Test;

import java.io.IOException;

public class DemoTest {
    @Test
    public void test() throws IOException {
        IniReader iniReader = new IniReader("src/test/resources/ini/my.ini");
        String name = iniReader.getValue("student", "username");
        String age = iniReader.getValue("student", "age");
        System.out.println(name);
        System.out.println(age);
    }
}

4.执行的结果如下:

zhangsan
20
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • feisky云计算、虚拟化与Linux技术笔记posts - 1014, comments - 298, trac...
    不排版阅读 3,937评论 0 5
  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 5,846评论 0 10
  • ORA-00001: 违反唯一约束条件 (.) 错误说明:当在唯一索引所对应的列上键入重复值时,会触发此异常。 O...
    我想起个好名字阅读 5,451评论 0 9
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,187评论 6 13
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,481评论 0 5