Saved YML files then move for reliability reasons

Instead of saving on top of a YML file, we now save to a tmp file and if
it is saved successfully, then it is moved on top of the old file in an
atomic move. This helps avoid data loss if the file write fails.
This commit is contained in:
tastybento 2018-06-17 17:15:44 -07:00
parent c03c1e3ecc
commit 8353d266a5

View File

@ -92,7 +92,15 @@ public class FlatFileDatabaseConnecter implements DatabaseConnecter {
tableFolder.mkdirs();
}
try {
yamlConfig.save(file);
// Approach is save to temp file (saving is not necessarily atomic), then move file atomically
// This has best chance of no file corruption
File tmpFile = File.createTempFile(tableName, ".tmp", tableFolder);
yamlConfig.save(tmpFile);
if (tmpFile.exists()) {
Files.move(tmpFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} else {
throw new Exception();
}
} catch (Exception e) {
plugin.logError("Could not save yaml file to database " + tableName + " " + fileName + " " + e.getMessage());
return;