Backup classifier data

This commit is contained in:
M66B 2021-05-08 11:23:22 +02:00
parent 644ff4ddae
commit 72e25340d3
1 changed files with 40 additions and 6 deletions

View File

@ -25,6 +25,7 @@ import android.os.Build;
import android.text.TextUtils;
import android.util.JsonReader;
import android.util.JsonWriter;
import android.util.MalformedJsonException;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
@ -390,6 +391,17 @@ public class MessageClassifier {
long start = new Date().getTime();
File file = getFile(context);
if (file.exists())
try {
File backup = getBackupFile(context);
Log.i("Classifier backup " + backup);
backup.delete();
file.renameTo(backup);
} catch (Throwable ex) {
Log.w(ex);
}
Log.i("Classifier save " + file);
try (JsonWriter writer = new JsonWriter(new BufferedWriter(new FileWriter(file)))) {
writer.beginObject();
@ -467,9 +479,31 @@ public class MessageClassifier {
return;
clear(context);
long start = new Date().getTime();
File file = getFile(context);
try {
_load(file);
} catch (MalformedJsonException ex) {
Log.w(ex);
clear(context);
File backup = getBackupFile(context);
if (backup.exists())
try {
_load(backup);
} catch (Throwable ex1) {
Log.e(ex1);
backup.delete();
clear(context);
}
} catch (Throwable ex) {
Log.e(ex);
file.delete();
clear(context);
}
}
private static synchronized void _load(File file) throws IOException {
Log.i("Classifier read " + file);
long start = new Date().getTime();
if (file.exists())
try (JsonReader reader = new JsonReader(new BufferedReader(new FileReader(file)))) {
reader.beginObject();
@ -599,10 +633,6 @@ public class MessageClassifier {
break;
}
reader.endObject();
} catch (Throwable ex) {
Log.e(ex);
file.delete();
clear(context);
}
loaded = true;
@ -654,6 +684,10 @@ public class MessageClassifier {
return new File(context.getFilesDir(), "classifier.json");
}
static File getBackupFile(@NonNull Context context) {
return new File(context.getFilesDir(), "classifier.backup");
}
private static class State {
private final List<String> words = new ArrayList<>();
private final Map<String, Stat> classStats = new HashMap<>();