@@ -207,23 +207,46 @@ static protected boolean isPlatformSpecific(String key, String value,
207207
208208
209209 static public void save () {
210- // on startup, don't worry about it
211- // this is trying to update the prefs for who is open
212- // before Preferences.init() has been called.
213- if (preferencesFile == null ) return ;
214-
215- // Fix for 0163 to properly use Unicode when writing preferences.txt
216- PrintWriter writer = PApplet .createWriter (preferencesFile );
217-
218- String [] keyList = table .keySet ().toArray (new String [table .size ()]);
219- // Sorting is really helpful for debugging, diffing, and finding keys
220- keyList = PApplet .sort (keyList );
221- for (String key : keyList ) {
222- writer .println (key + "=" + table .get (key )); //$NON-NLS-1$
223- }
210+ // On startup it'll be null, don't worry about it. It's trying to update
211+ // the prefs for the open sketch before Preferences.init() has been called.
212+ if (preferencesFile != null ) {
213+ try {
214+ File dir = preferencesFile .getParentFile ();
215+ File preferencesTemp = File .createTempFile ("preferences" , ".txt" , dir );
216+
217+ // Fix for 0163 to properly use Unicode when writing preferences.txt
218+ PrintWriter writer = PApplet .createWriter (preferencesTemp );
224219
225- writer .flush ();
226- writer .close ();
220+ String [] keyList = table .keySet ().toArray (new String [table .size ()]);
221+ // Sorting is really helpful for debugging, diffing, and finding keys
222+ keyList = PApplet .sort (keyList );
223+ for (String key : keyList ) {
224+ writer .println (key + "=" + table .get (key )); //$NON-NLS-1$
225+ }
226+ writer .flush ();
227+ writer .close ();
228+
229+ // Rename preferences.txt to preferences.old
230+ File oldPreferences = new File (dir , "preferences.old" );
231+ if (oldPreferences .exists ()) {
232+ if (!oldPreferences .delete ()) {
233+ throw new IOException ("Could not delete preferences.old" );
234+ }
235+ }
236+ if (!preferencesFile .renameTo (oldPreferences )) {
237+ throw new IOException ("Could not replace preferences.old" );
238+ }
239+
240+ // Make the temporary file into the real preferences
241+ if (!preferencesTemp .renameTo (preferencesFile )) {
242+ throw new IOException ("Could not move preferences file into place" );
243+ }
244+
245+ } catch (IOException e ) {
246+ Messages .showWarning ("Preferences" ,
247+ "Could not save the Preferences file." , e );
248+ }
249+ }
227250 }
228251
229252
0 commit comments