Forráskód Böngészése

overwrite settings atomically

Sebastian Stenzel 6 éve
szülő
commit
367281fccb

+ 6 - 3
main/commons/src/main/java/org/cryptomator/common/settings/SettingsProvider.java

@@ -29,6 +29,7 @@ import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.NoSuchFileException;
 import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
 import java.nio.file.StandardOpenOption;
 import java.util.Optional;
 import java.util.concurrent.Executors;
@@ -109,11 +110,13 @@ public class SettingsProvider implements Provider<Settings> {
 		LOG.debug("Attempting to save settings to {}", settingsPath);
 		try {
 			Files.createDirectories(settingsPath.getParent());
-			try (OutputStream out = Files.newOutputStream(settingsPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); //
-					Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
+			Path tmpPath = settingsPath.resolveSibling(settingsPath.getFileName().toString() + ".tmp");
+			try (OutputStream out = Files.newOutputStream(tmpPath, StandardOpenOption.CREATE_NEW); //
+				 Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
 				gson.toJson(settings, writer);
-				LOG.info("Settings saved to {}", settingsPath);
 			}
+			Files.move(tmpPath, settingsPath, StandardCopyOption.REPLACE_EXISTING);
+			LOG.info("Settings saved to {}", settingsPath);
 		} catch (IOException e) {
 			LOG.error("Failed to save settings.", e);
 		}