使用groovy更新行而不删除文件的内容

时间:2018-04-05 12:37:16

标签: java groovy

这里我想更新现有文件中一行的内容 但是,当我运行此代码时,我得到一个空文件。如何解决这个问题?

这是代码源:

 def headerFilePattern = ~/^\d{1,2}-Header\.csv\u0024/
 final String PATH_SEPARATOR = "\\"
 String directoryPath = "C:\\directory"
 final String CHARACTER_ENCODING = "UTF-8"
 final String FILE_SEPARATOR = "="
 def linePattern = ~/\$\w.*=.*/
 def $_ = "\u0024"

 File directory = new File(directoryPath)

 println "Matching Files:"
 directory.eachFileRecurse({
     if (headerFilePattern.matcher(it.name).find()) {
         println "\t${it.name} (size ${it.size()})"
         File headerFile = new File(directoryPath + PATH_SEPARATOR + it.name);
         headerFile.withWriter { w ->
             headerFile.eachLine { line ->
                 if (linePattern.matcher(line)) {
                     def (key, value) = line.tokenize(FILE_SEPARATOR)
                     println "key : " + key
                     println "value : " + value
                     if (key == "${$_}countryCode") {
                         w << line.replaceAll( value, "World!!!21" )
                     }
                 }     
             }
         }
     }
 })

1 个答案:

答案 0 :(得分:0)

我创建原始文件的副本以从中读取并写入原始文件然后删除副本。我不知道这是否是我问题的最佳解决方案:) !!!