I'm trying some stuff in Android at the moment, and I'm trying to save some data to JSON using GSON and also append new data to the same file.
Let's say that this is the first time the code is being run, and the data is being saved to a file called test.json:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
ArrayList<GSONObject> objects = new ArrayList<GSONObject>();
GSONObject obj = new GSONObject("sth", 1, 1345939200000);
objects.add(obj);
String json = gson.toJson(objects);
File file = new File(filePath + fileName);
FileWriter fileWriter = new FileWriter(file, true);
fileWriter.append(json);
fileWriter.close();
Now I have this saved to the file:
[ {
"something": "sth",
"id": 1,
"time": 1345939200000
} ]
Later i want to run the app again, but then append some new data to the same file so that it looks like this:
[ {
"sth": "sth",
"id": 1,
"time": 1345939200000
},
{
"sth": "sth2",
"id": 2,
"time": 1345939500000
} ]
I am trying to save the amount of data and memory used in this process, so parsing the file into memory first and then write it back to the file is something I'd rather avoid.
Any suggestions? It really doesn't have to be GSON, just something that works well.
EDIT: I have made a solution to the problem with some of the suggestions from maaartinus. You can see it here, and contribute if you know a better solution!