1

I'm trying to add multiple-values option into my ini file from Groovy using ini4j with following codes (I tried some variants):

import org.ini4j.Wini 
List valuesList = [ 'val1’, ‘val2’, ‘val3' ] 
( new Wini( new File( "test.ini" ) ) ).with{
     valuesList.each{
          put( 'sectionNa'sectionName','optionName', it)
    }
    store()
}

import org.ini4j.Wini
List valuesList = [ 'val1’, ‘val2’, ‘val3' ]
( new Wini( new File( "test.ini" ) ) ).with{
    Section sectionObject = get( ‘sectionName’ )
    sectionObject .put( 'optionName', ‘val1’ )
    sectionObject .put( 'optionName', ‘val2’ )
    sectionObject .put( 'optionName', ‘val3’ )
    }
    store()
}

I got ini file like this one:

[sectionName]
optionName = val3

But I want to get:

[sectionName]
optionName = val1
optionName = val2
optionName = val3

Could you please advice me how to resolve my issue? Thanks In Advance!

Update 1

I still waiting more elegant solution. But I created direct ini file editing below. Please provide me any feedback about it:

List newLines = []
File currentFile = new File( "test.ini" )
List currentLines = currentFile.readLines()
int indexSectionStart = currentLines.indexOf( 'sectionName' )
(0..indexSectionStart).each{
    newLines.add( currentLines[ it ] )
}
List valuesList = 'val1,val2,val3'.split( ',' )
valuesList.each{
        newLines.add( "optionName = $it" )
}   
( indexSectionStart + 1 .. currentLines.size() - 1 ).each{
    newLines.add( currentLines[ it ] )
}
File newFile = new File( "new_test.ini" )
if ( newFile.exists() ) newFile.delete()
newLines.each {
    newFile.append( it+'\n' )
}

And simply delete old file and rename new one. I implemented it because I didn't find any insertLine() like methods in standart File

4

1 回答 1

0

对了,怎么样:

import org.ini4j.*

List valuesList = [ 'val1', 'val2', 'val3' ] 

new File( "/tmp/test.ini" ).with { file ->
    new Wini().with { ini ->
        // Configure to allow multiple options
        ini.config = new Config().with { it.multiOption = true ; it }

        // Load the ini file
        ini.load( file )

        // Get or create the section
        ( ini.get( 'sectionName' ) ?: ini.add( 'sectionName' ) ).with { section ->
            valuesList.each {

                // Then ADD the options
                section.add( 'optionName', it )
            }
        }

        // And write it back out
        store( file )
    }
}
于 2013-07-23T13:56:46.840 回答