如何删除 Java 文本文件中的最后两行?

How can I remove last 2 lines in text file in Java?

我想使用 java 删除文本文件中的最后两行。我为此尝试了 4 或 5 种不同的方法,但找不到工作代码。我将这样编辑文件:

[
    {
        "example"
    }
]

我想删除“]”、“}”并添加“example2”。我怎样才能做到这一点 ? (我使用的是 SE 1.8 ,也许版本对此有影响)

你能推荐什么吗?

谢谢。

您可以尝试读取文件,然后重新写入但不要最后两行:

public void removeLastLines() {
    int lines = 2; //This is the number that determines how many we remove
    try(BufferedReader br = new BufferedReader(new FileReader(file))){
        List<String> lineStorage = new ArrayList<>();
        String line;
        while((line=br.readLine()) !=null) {
            lineStorage.add(line);
        }
        try(BufferedWriter bw = new BufferedWriter(new FileWriter(file))){
            int lines1 = lineStorage.size()-lines;
            for(int i = 0; i < lines1; i++) {
                bw.write(lineStorage.get(i));
                bw.newLine();
            }
        }
    }catch(Exception e) {
        e.printStackTrace();
    }
}