Make file writes more resilient to crashes to avoid loss of data

This commit is contained in:
bancika
2020-09-02 08:48:02 +02:00
parent 7628eefd6d
commit 5591724a67
2 changed files with 14 additions and 5 deletions
@@ -3134,6 +3134,10 @@
<changeType>IMPROVEMENT</changeType> <changeType>IMPROVEMENT</changeType>
<description>Improved Dutch translation</description> <description>Improved Dutch translation</description>
</org.diylc.appframework.update.Change> </org.diylc.appframework.update.Change>
<org.diylc.appframework.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Make file writes more resilient to crashes to avoid loss of data</description>
</org.diylc.appframework.update.Change>
<org.diylc.appframework.update.Change> <org.diylc.appframework.update.Change>
<changeType>BUG_FIX</changeType> <changeType>BUG_FIX</changeType>
<description>"Outline Mode" produces rendering issues when "Cache Boost" feature is enabled</description> <description>"Outline Mode" produces rendering issues when "Cache Boost" feature is enabled</description>
@@ -148,14 +148,19 @@ public class ProjectFileManager {
public synchronized void serializeProjectToFile(Project project, String fileName, boolean isBackup) public synchronized void serializeProjectToFile(Project project, String fileName, boolean isBackup)
throws IOException { throws IOException {
if (!isBackup) { if (!isBackup) {
LOG.info(String.format("saveProjectToFile(%s)", fileName)); LOG.info(String.format("serializeProjectToFile(%s)", fileName));
} }
FileOutputStream fos; FileOutputStream fos;
fos = new FileOutputStream(fileName); // write to a temp file to avoid loss of data in case of crash
String tempName = fileName + ".temp";
fos = new FileOutputStream(tempName);
Writer writer = new OutputStreamWriter(fos, "UTF-8"); Writer writer = new OutputStreamWriter(fos, "UTF-8");
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
xStream.toXML(project, writer); xStream.toXML(project, writer);
fos.close(); fos.close();
// switch the files at the end
new File(fileName).delete();
new File(tempName).renameTo(new File(fileName));
if (!isBackup) { if (!isBackup) {
this.currentFileName = fileName; this.currentFileName = fileName;
this.modified = false; this.modified = false;