gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:32:45 26 4
gpt4 key购买 nike

我正在尝试使用 ini4j 和以下代码将多值选项添加到 Groovy 的 ini 文件中(我尝试了一些变体):

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

我有这样的 ini 文件:

[sectionName]
optionName = val3

但我想得到:

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

您能否建议我如何解决我的问题?提前致谢!

更新1

我还在等待更优雅的解决方案。但我在下面创建了直接 ini 文件编辑。请向我提供任何有关它的反馈:

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

只需删除旧文件并重命名新文件即可。我实现它是因为我在标准 File 中没有找到任何类似于 insertLine() 的方法

最佳答案

对了,这个怎么样:

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

关于java - Groovy/Java : Ini4j insert multiple values to single parameter in different lines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17786289/

26 4 0