使用 groovy 附加到文件中的某个行号

mor*_*wgi 3 groovy

我没有附加到文件的末尾,而是尝试使用常规File操作替换或附加到某一行。

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

def file = new File("newFilename")
file.append("I wish to append this to line 8")
Run Code Online (Sandbox Code Playgroud)

ata*_*lor 5

通常,使用 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
    }
}
Run Code Online (Sandbox Code Playgroud)