I need to save objects in one file. I use Gson library. Writing to file is easy, but reading is complicated. I read whole file char by char, but this solution is inefficient. How to read only one JSON string? I have no idea how to do it better.
File file = new File(getContext().getFilesDir(), "slovicka.json");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
char s;
char z = '{';
char z2 = '}';
int zavorky = 0;
String j = "";
p = 0;
while (true) {
s = (char) br.read();
if (s == z) {
zavorky++;
}
if (s == z2) {
zavorky--;
}
j = j + s;
if (zavorky == 0) {
Gson gson = new Gson();
SlovickoS slovos = gson.fromJson(j, SlovickoS.class);
list.add(slovo);
j = "";
}
}
} catch (Exception e) {
System.out.println("Chyba při čtení ze souboru.");
}