Rename the file. Handle possible OS specific issues
16268
private static void moveFile(final File fromFile, final File toFile) throws UpdateException {
        try {
            // Create parent directory structure if necessary
            FileUtils.mkParentDirs(toFile);
            Files.move(fromFile.toPath(), toFile.toPath(),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException ioe) {
            throw new UpdateException("Unable to move temporary file to destination file: " +
                    fromFile + " -> " + toFile + ": " + ioe.toString());
        }
    }
304650
private void rename(String from, String to) throws IOException
   {
      IndexOutputStream out = null;
      IndexInputStream in = null;
      try
      {
         out = new IndexOutputStream(dir.createOutput(to));
         in = new IndexInputStream(dir.openInput(from));
         DirectoryHelper.transfer(in, out);
      }
      finally
      {
         if (in != null)
         {
            in.close();
         }

         if (out != null)
         {
            out.flush();
            out.close();
         }
      }
      try
      {
         // delete old one
         if (dir.fileExists(from))
         {
            dir.deleteFile(from);
         }
      }
      catch (IOException e)
      {
         // do noting. Will be removed later
         if (LOG.isTraceEnabled())
         {
            LOG.trace("Can't deleted file: " + e.getMessage());
         }
      }
   }
1234548
def rename_script(rename=None):  # noqa: E501
    
    if connexion.request.is_json:
        rename = Rename.from_dict(connexion.request.get_json())  # noqa: E501

    if(not hasAccess()):
        return redirectUnauthorized()

    driver = LoadedDrivers.getDefaultDriver()
    if (not driver.renameScript(rename.original.name, rename.new.name)):
        return ErrorResponse(status=500, message='Cannot rename to an existing file.')
    return Response(status=200, body={'file-name': rename.new.name})
1037631
def os_replace(src, dst):
    '''
    
    '''

    orig_os_replace_func = getattr(os, 'replace', None)

    if orig_os_replace_func is not None:
        # not need for emulation: we using modern version of Python.
        # fully atomic for this case

        orig_os_replace_func(src, dst)
        return

    if os.name == 'posix':
        # POSIX requirement: `os.rename(..)` works as `os.replace(..)`
        # fully atomic for this case

        os.rename(src, dst)
        return

    # simple emulation for `os.name == 'nt'` and other marginal
    # operation systems.  not fully atomic implementation for this
    # case

    try:
        # trying atomic `os.rename(..)` without `os.remove(..)` or
        # other operations

        os.rename(src, dst)
        error = None
    except OSError as e:
        error = e

    if error is None:
        return

    for i in range(5):
        # some number of tries may be failed
        # because we may be in concurrent environment with other
        # processes/threads

        try:
            os.remove(dst)
        except OSError:
            # destination was not exist
            # or concurrent process/thread is removing it in parallel with us
            pass

        try:
            os.rename(src, dst)
            error = None
        except OSError as e:
            error = e
            continue

        break

    if error is not None:
        raise_from(OSError('failed to replace'), error)
497246
def safe_delete(filename):
  """"""
  try:
    os.unlink(filename)
  except OSError as e:
    if e.errno != errno.ENOENT:
      raise
942515
def renames(old, new):
    # type: (str, str) -> None
    """"""
    # Implementation borrowed from os.renames().
    head, tail = os.path.split(new)
    if head and tail and not os.path.exists(head):
        os.makedirs(head)

    shutil.move(old, new)

    head, tail = os.path.split(old)
    if head and tail:
        try:
            os.removedirs(head)
        except OSError:
            pass
370141
def change_filename(filehandle, meta):
    
    filename = secure_filename(meta.get('filename', filehandle.filename))
    basename, _ = os.path.splitext(filename)
    meta['original_filename'] = filehandle.filename
    filehandle.filename = filename + '.jpg'
    return filehandle
460186
def rename_dont_move(self, path, dest):
        
        self.move(path, dest, raise_if_exists=True)
392746
def file_renamed(self, editor, new_filename):
        """"""
        if editor is None:
            # This is needed when we can't find an editor to attach
            # the outline explorer to.
            # Fix issue 8813
            return
        editor_id = editor.get_id()
        if editor_id in list(self.editor_ids.values()):
            root_item = self.editor_items[editor_id]
            root_item.set_path(new_filename, fullpath=self.show_fullpath)
            self.__sort_toplevel_items()
492494
public void rename(String oldName, String newName)
        throws IOException, ServerException {
        if (oldName == null || newName == null) {
            throw new IllegalArgumentException("Required argument missing");
        }
        Command cmd = new Command("RNFR", oldName);
        try {
            Reply reply = controlChannel.exchange(cmd);
            if (!Reply.isPositiveIntermediate(reply)) {
                throw new UnexpectedReplyCodeException(reply);
            }
            controlChannel.execute(new Command("RNTO", newName));
        } catch (FTPReplyParseException rpe) {
            throw ServerException.embedFTPReplyParseException(rpe);
        } catch (UnexpectedReplyCodeException urce) {
            throw ServerException.embedUnexpectedReplyCodeException(
                                urce,
                                "Server refused renaming file");
        }
    }
344734
function reFile(filename, nfilename) {
    return new Promise(function (fulfill, reject) {
        fs.rename(filename, nfilename, function (err) {
            return err ? reject(err) : fulfill();
        });
    });
}
832499
def fix_file(self, file_name):
        
        # We hope that a CalledProcessError would have already raised
        # during the init if it were going to raise here.
        modified_lines = self.modified_lines(file_name)

        return fix_file(file_name, modified_lines, self.options,
                        in_place=self.in_place, diff=True,
                        verbose=self.verbose, cwd=self.cwd)
350621
def normalize_ext_rename(filepath):
    
    logger.debug('normalize_ext.filepath=' + str(filepath))
    new_file_path = normalize_ext(filepath)
    logger.debug('download_unzip.new_filepaths=' + str(new_file_path))
    # FIXME: fails when name is a url filename
    filepath = rename_file(filepath, new_file_path)
    logger.debug('download_unzip.filepath=' + str(filepath))
    return filepath
414043
def rename(self, new_path):
        
        rename_path = fix_raw_path(new_path)
        if is_folder(self.path):
            os.rename(self.path, rename_path)
        else:
            os.renames(self.path, rename_path)
67137
def on_exists(fname):
    # type: (str) -> None
    

    if os.path.isfile(fname):
        newfile = fname + ".old"
        print("{} -> {}".format(fname, newfile))
        os.rename(fname, newfile)
849637
public static void replaceFile(File src, File target) throws IOException {
    /* renameTo() has two limitations on Windows platform.
     * src.renameTo(target) fails if
     * 1) If target already exists OR
     * 2) If target is already open for reading/writing.
     */
    if (!src.renameTo(target)) {
      int retries = 5;
      while (target.exists() && !target.delete() && retries-- >= 0) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          throw new IOException("replaceFile interrupted.");
        }
      }
      if (!src.renameTo(target)) {
        throw new IOException("Unable to rename " + src +
                              " to " + target);
      }
    }
  }
990395
function rename(oldPath, newPath, callback) {
        appshell.fs.rename(oldPath, newPath, _wrap(callback));
    }