I am creating a game and I am in the part of creating monsters and I need a json file to save the monsters but when I create a new monsters it writes on top of what already exists as I can only add a new monster.
Code:
import org.json.*;
import java.io.*;
import java.util.*;
import java.util.Random;
public class Jsonarquivo {
public static void main(String[] args) throws IOException, JSONException {
File arq = new File("Monstros.Potato");
if(arq.exists() && !arq.isDirectory()){
JSONObject mons_data = new JSONObject();
mons_data.put("Monstro", "Lobo");
mons_data.put("Level", 2);
mons_data.put("HP", 100);
JSONArray mons_array = new JSONArray();
mons_array.put(mons_data);
JSONObject main_data = new JSONObject();
main_data.put("data", mons_array);
FileWriter fw = new FileWriter(arq);
PrintWriter fw_pw = new PrintWriter(fw);
String save = main_data.toString();
fw_pw.println(save);
fw.close();
}
else{
arq.createNewFile();
JSONObject mons_data = new JSONObject();
mons_data.put("Monstro", "Bruxa");
mons_data.put("Level", 1);
mons_data.put("HP", 1);
JSONArray mons_array = new JSONArray();
mons_array.put(mons_data);
JSONObject main_data = new JSONObject();
main_data.put("Data", mons_array);
FileWriter fw = new FileWriter(arq);
PrintWriter fw_pw = new PrintWriter(fw);
String save = main_data.toString();
fw_pw.print(save);
fw.close();
}
}
}
Output:
{"data":[{"HP":100,"Monstro":"Lobo","Level":2}]}
How do I need it to stay:
{"data":[{"HP":100,"Monstro":"Lobo","Level":2}{"HP":150,"Monstro":"Bruxa","Level":3}]}
NOTE: The game and infinity the hp and level are generated based on some accounts, and as the player adds more monsters the data of him is placed here. already tried several things but it does not work.