Search code examples
javafile-iogroovyiniini4j

Groovy/Java: Ini4j insert multiple values to single parameter in different lines


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


Solution

  • Right, how's this:

    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 )
        }
    }