Groovy读取INI文件代码

工作上需要一个读取INI文件的需求,想到如何用Groovy实现,写了段简单代码,欢迎评论
INI文件示例
[Section1]
key1=value1
key2=value2

[Section2]
key1=value1
key2=value2

Groovy代码
class  IniReader {
    def sections = [:]

    void read(String fileName) {
        def currentSectionName, properties
        new File(fileName).eachLine() { line ->
            if(line != '') {
                if(line.startsWith('[') && line.endsWith(']')) {
                    currentSectionName = line - '[' - ']'
                    properties = [:]                    
                } else {
                    def kv = line.split('=')
                    properties[kv[0]] = kv[1]
                    sections[currentSectionName] = properties
                }
            }
        }
    }
}


测试程序
IniReader iReader = new IniReader()
iReader.read('./test.ini')
def sections = iReader.getSections()
// 取值 [Section1] key1
def section = sections['Section1']
println section['key1']


你可能感兴趣的:(java,工作,groovy)