From 4e4abf8a54fd97d2bba969229bc607676f632345 Mon Sep 17 00:00:00 2001 From: Mike Hearn Date: Fri, 8 Jun 2012 17:10:35 +0200 Subject: [PATCH] Delete the wallet file before renaming its replacement on Windows. Resolves issue 200. --- .../java/com/google/bitcoin/core/Wallet.java | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/core/src/main/java/com/google/bitcoin/core/Wallet.java b/core/src/main/java/com/google/bitcoin/core/Wallet.java index f366b80e4..8e17c93a4 100644 --- a/core/src/main/java/com/google/bitcoin/core/Wallet.java +++ b/core/src/main/java/com/google/bitcoin/core/Wallet.java @@ -186,22 +186,26 @@ public class Wallet implements Serializable { */ public synchronized void saveToFile(File f) throws IOException { FileOutputStream stream = null; - File temp = null; + File temp; try { File directory = f.getAbsoluteFile().getParentFile(); temp = File.createTempFile("wallet", null, directory); stream = new FileOutputStream(temp); saveToFileStream(stream); + // Attempt to force the bits to hit the disk. In reality the OS or hard disk itself may still decide + // to not write through to physical media for at least a few seconds, but this is the best we can do. + stream.flush(); + stream.getFD().sync(); + if (!temp.renameTo(f)) { + // Work around an issue on Windows whereby you can't rename over existing files. + if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { + if (f.delete() && temp.renameTo(f)) return; // else fall through. + } + throw new IOException("Failed to rename " + temp + " to " + f); + } } finally { if (stream != null) { - // Attempt to force the bits to hit the disk. In reality the OS or hard disk itself may still decide - // to not write through to physical media for at least a few seconds, but this is the best we can do. - stream.flush(); - stream.getFD().sync(); stream.close(); - if (!temp.renameTo(f)) { - throw new IOException("Failed to rename " + temp + " to " + f); - } } } }