Code with Finding: |
class FSDirectory {
/** Renames an existing file in the directory.
* Warning: This is not atomic.
* @deprecated
*/
public synchronized void renameFile(String from, String to)
throws IOException {
ensureOpen();
File old = new File(directory, from);
File nu = new File(directory, to);
/* This is not atomic. If the program crashes between the call to
delete() and the call to renameTo() then we're screwed, but I've
been unable to figure out how else to do this... */
if (nu.exists())
if (!nu.delete())
throw new IOException("Cannot delete " + nu);
// Rename the old file to the new one. Unfortunately, the renameTo()
// method does not work reliably under some JVMs. Therefore, if the
// rename fails, we manually rename by copying the old file to the new one
if (!old.renameTo(nu)) {
java.io.InputStream in = null;
java.io.OutputStream out = null;
try {
in = new FileInputStream(old);
out = new FileOutputStream(nu);
// see if the buffer needs to be initialized. Initialization is
// only done on-demand since many VM's will never run into the renameTo
// bug and hence shouldn't waste 1K of mem for no reason.
if (buffer == null) {
buffer = new byte[1024];
}
int len;
while ((len = in.read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
// delete the old file.
old.delete();
}
catch (IOException ioe) {
IOException newExc = new IOException("Cannot rename " + old + " to " + nu);
newExc.initCause(ioe);
throw newExc;
}
finally {
try {
if (in != null) {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException("Cannot close input stream: " + e.toString(), e);
}
}
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException("Cannot close output stream: " + e.toString(), e);
}
}
}
}
}
}
}
|