groovy - 使用 groovy 附加到文件中的特定行号

标签 groovy

我尝试使用常规 File 操作替换或附加到特定行,而不是追加到文件末尾。

有没有办法做到这一点? append 添加到文件末尾,而 write 覆盖现有文件:

def file = new File("newFilename")
file.append("I wish to append this to line 8")

最佳答案

通常,对于 Java 和 Groovy 文件处理,您只能追加到文件末尾。无法插入信息,尽管您可以在任何地方覆盖数据而无需移动后面内容的位置。

这意味着要附加到不在文件末尾的特定行,您需要重写整个文件。

例如:

def file = new File("newFilename")
new File("output").withPrintWriter { out ->
    def linenumber = 1
    file.eachLine { line ->
        if (linenumber == 8)
            out.print(line)
            out.println("I wish to append this to line 8")
        } else {
            out.println(line)
        }
        linenumber += 1
    }
}

关于groovy - 使用 groovy 附加到文件中的特定行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34881692/

相关文章:

java - 你如何设置一个也可以使用 groovy 的 maven java 项目?

grails - 找不到构造函数 'java.lang.String'的参数0

intellij-idea - 如何使用IntelliJ Live Template 内部?

regex - groovy 正则表达式

Elasticsearch : filter on scripted sum of filtered nested field

jenkins - Jenkins Groovy 脚本中的预期步骤

groovy - Gradle 构建不包括 source/src groovy

jenkins - 将 map 传递到 Jenkins 管道作业

java - Grails:events.PatchedDefaultFlushEventListener - 无法将数据库状态与 session org.hibernate.StaleObjectStateException 同步

logging - Groovy 和 Spock - 使用 @Slf4j AST 标签,检测日志记录事件