2
I’m creating a game and I’m in the monster part and I need a json file to save the monsters but when I create a new monster it writes on top of what already exists as I arrange to just 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();
}
}
}
Exit:
{"data":[{"HP":100,"Monstro":"Lobo","Level":2}]}
How I need you to stay:
{"data":[{"HP":100,"Monstro":"Lobo","Level":2}{"HP":150,"Monstro":"Bruxa","Level":3}]}
NOTE: the game and infinity hp and level are generated based on a few accounts, and Form the player add more monsters their data be placed here. I’ve tried a lot of things.