且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Java替换文件中的特定行?

更新时间:2023-01-15 18:02:16

如果您使用的是Java 7或更高版本,并且lineNumber从1开始,则可以执行以下操作:

If you are using Java 7 or higher and if lineNumber starts in 1, you can do the following:

public static void setVariable(int lineNumber, String data) throws IOException {
    Path path = Paths.get("data.txt");
    List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
    lines.set(lineNumber - 1, data);
    Files.write(path, lines, StandardCharsets.UTF_8);
}

很明显,如果lineNumber从0开始,则:

Obviously if lineNumber starts in 0, then:

lines.set(lineNumber, data);