我尝试使用常规 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/