gpt4 book ai didi

java - 如何编码以便我不会添加重复记录而不是覆盖 txt 文件中的内容

转载 作者:行者123 更新时间:2023-12-02 09:13:31 25 4
gpt4 key购买 nike

import java.io.*;

public class SaveGame {

public static void main(String[] args) {
String user = "John";//rewrite as String user = String.toString(Game.user)
String compTime1 = "2";
String compTime2 = "0";
String compTime3 = "0";
String compLevel = "2";
String tokenCollected = "3";
String flipperCollected = "2";
String firebootsCollected = "4";
String wingbootsCollected = "3";
String keysCollected = "3";

saveGame(user,compTime1,compTime2,compTime3,compLevel, tokenCollected, flipperCollected,firebootsCollected,wingbootsCollected,keysCollected);
}

public static void saveGame(String user, String compTime1, String compTime2, String compTime3, String compLevel, String tokenCollected, String flipperCollected, String firebootsCollected, String wingbootsCollected, String keysCollected) {
try
{
FileWriter fw = new FileWriter("Game.txt",true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);

pw.print("\n" +user + "," + compTime1 + "," + compTime2 + "," + compTime3 + "," + compLevel + "," + tokenCollected + "," + flipperCollected + "," + firebootsCollected + "," + wingbootsCollected + "," + keysCollected);
pw.flush();
pw.close();
} catch(Exception e) {
e.printStackTrace();
System.out.println("Record not saved");
}
}
}

我应该写什么,以便当我添加名称为 John 的数据时,该数据已存在于 game.txt 文件中,不会再次添加,而是会覆盖其中包含 John 的记录在 game.txt 中。我发现只有添加有效。

最佳答案

如果文件不大,您可以将整个文件读取到内存中。将读取的字符串数据解析为对象列表或映射。然后应用新的更改并将整个 block 重新写入文件。您可以将对象的 map 或列表传递给写入函数。

关于java - 如何编码以便我不会添加重复记录而不是覆盖 txt 文件中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59200405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com