Example usage for java.io File renameTo

List of usage examples for java.io File renameTo

Introduction

In this page you can find the example usage for java.io File renameTo.

Prototype

public boolean renameTo(File dest) 

Source Link

Document

Renames the file denoted by this abstract pathname.

Usage

From source file:com.ephesoft.dcma.gwt.foldermanager.server.FolderManagerServiceImpl.java

@Override
public Boolean renameFile(String oldName, String newName, String folderPath) {
    File orignalFile = new File(folderPath + File.separator + oldName);
    File renamedFile = new File(folderPath + File.separator + newName);
    return orignalFile.renameTo(renamedFile);
}

From source file:com.thruzero.common.core.fs.walker.visitor.FileRenamingVisitor.java

protected void doRenameFileOrDirectory(final File fileOrDir) throws IOException {
    String newName = substitutionStrategy.replaceAll(fileOrDir.getName());

    if (StringUtils.isNotEmpty(newName) && !fileOrDir.getName().equals(newName)) {
        if (logger.isDebugEnabled()) {
            logger.debug("  - renaming file = " + fileOrDir.getName() + " to " + newName);
        }/*from   w  w w.jav  a  2 s . c  om*/
        fileOrDir.renameTo(new File(fileOrDir.getParent(), newName));
        getStatus().incNumProcessed();
    }
}

From source file:de.sub.goobi.helper.FilesystemHelper.java

/**
 * This function implements file renaming. Renaming of files is full of
 * mischief under Windows which unaccountably holds locks on files.
 * Sometimes running the JVMs garbage collector puts things right.
 *
 * @param oldFileName//w  w w.  j av  a  2  s.co m
 *            File to move or rename
 * @param newFileName
 *            New file name / destination
 * @throws IOException
 *             is thrown if the rename fails permanently
 * @throws FileNotFoundException
 *             is thrown if old file (source file of renaming) does not
 *             exists
 */
public static void renameFile(String oldFileName, String newFileName) throws IOException {
    final int SLEEP_INTERVAL_MILLIS = 20;
    final int MAX_WAIT_MILLIS = 150000; // 2 minutes
    File oldFile;
    File newFile;
    boolean success;
    int millisWaited = 0;

    if ((oldFileName == null) || (newFileName == null)) {
        return;
    }

    oldFile = new File(oldFileName);
    newFile = new File(newFileName);

    if (!oldFile.exists()) {
        if (logger.isDebugEnabled()) {
            logger.debug("File " + oldFileName + " does not exist for renaming.");
        }
        throw new FileNotFoundException(oldFileName + " does not exist for renaming.");
    }

    if (newFile.exists()) {
        String message = "Renaming of " + oldFileName + " into " + newFileName + " failed: Destination exists.";
        logger.error(message);
        throw new IOException(message);
    }

    do {
        if (SystemUtils.IS_OS_WINDOWS && millisWaited == SLEEP_INTERVAL_MILLIS) {
            if (logger.isEnabledFor(Level.WARN)) {
                logger.warn("Renaming " + oldFileName
                        + " failed. This is Windows. Running the garbage collector may yield good results. Forcing immediate garbage collection now!");
            }
            System.gc();
        }
        success = oldFile.renameTo(newFile);
        if (!success) {
            if (millisWaited == 0 && logger.isInfoEnabled()) {
                logger.info("Renaming " + oldFileName + " failed. File may be locked. Retrying...");
            }
            try {
                Thread.sleep(SLEEP_INTERVAL_MILLIS);
            } catch (InterruptedException e) {
            }
            millisWaited += SLEEP_INTERVAL_MILLIS;
        }
    } while (!success && millisWaited < MAX_WAIT_MILLIS);

    if (!success) {
        logger.error("Rename " + oldFileName + " failed. This is a permanent error. Giving up.");
        throw new IOException("Renaming of " + oldFileName + " into " + newFileName + " failed.");
    }

    if (millisWaited > 0 && logger.isInfoEnabled()) {
        logger.info("Rename finally succeeded after" + Integer.toString(millisWaited) + " milliseconds.");
    }
}

From source file:com.derbysoft.common.log4j.DailyRollingFileAppender.java

/**
 * Rollover the current file to a new file.
 *///from   ww w  . ja  v  a  2s .co  m
void rollOver() throws IOException {

    /* Compute filename, but only if datePattern is specified */
    if (datePattern == null) {
        errorHandler.error("Missing DatePattern option in rollOver().");
        return;
    }

    String datedFilename = fileName + sdf.format(now);
    // It is too early to roll over because we are still within the
    // bounds of the current interval. Rollover will occur once the
    // next interval is reached.
    if (scheduledFilename.equals(datedFilename)) {
        return;
    }

    // close current file, and rename it to datedFilename
    this.closeFile();

    File target = new File(scheduledFilename);
    if (target.exists()) {
        if (!target.delete()) {
            LogLog.error("Failed to delete [" + scheduledFilename + "].");
        }
    }

    File file = new File(fileName);
    boolean result = file.renameTo(target);
    if (result) {
        LogLog.debug(fileName + " -> " + scheduledFilename);
    } else {
        LogLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "].");
    }

    try {
        // This will also close the file. This is OK since multiple
        // close operations are safe.
        this.setFile(fileName, true, this.bufferedIO, this.bufferSize);
    } catch (IOException e) {
        errorHandler.error("setFile(" + fileName + ", true) call failed.");
    }
    scheduledFilename = datedFilename;
}

From source file:eu.scape_project.planning.manager.FileStorage.java

@Override
public String store(String pid, byte[] bytestream) throws StorageException {
    String objectId;/* w  ww .jav a2  s . c  o  m*/
    if (pid == null) {
        // a new object
        objectId = UUID.randomUUID().toString();
        pid = repositoryName + ":" + objectId;
    } else {
        // we ignore the object's namespace
        objectId = pid.substring(pid.indexOf(':') + 1);
    }
    // we try to rename the file, if it already exists
    File file = new File(storagePathFile, objectId);
    File backup = null;
    if (file.exists()) {
        try {
            backup = File.createTempFile(file.getName(), "backup", storagePathFile);
            file.renameTo(backup);
        } catch (IOException e) {
            throw new StorageException("failed to create backup for: " + pid, e);
        }
    }
    try {
        // write data to filesystem
        FileUtils.writeToFile(new ByteArrayInputStream(bytestream), new FileOutputStream(file));
        // data was stored successfully, backup is not needed any more
        if (backup != null) {
            backup.delete();
        }
    } catch (IOException e) {
        // try to restore old file
        if (backup != null) {
            if (backup.renameTo(file)) {
                backup = null;
            } else {
                throw new StorageException(
                        "failed to store digital object: " + pid + " and failed to restore backup!");
            }
        }
        throw new StorageException("failed to store digital object: " + pid, e);
    }
    return pid;

}

From source file:ddf.catalog.backup.CatalogBackupPlugin.java

private void renameTempFile(File source) throws IOException {
    File destination = new File(StringUtils.removeEnd(source.getAbsolutePath(), TEMP_FILE_EXTENSION));
    boolean success = source.renameTo(destination);
    if (!success) {
        LOGGER.warn("Failed to move {} to {}.", source.getAbsolutePath(), destination.getAbsolutePath());
    }//w  ww  . jav a2s  . co  m
}

From source file:com.doplgangr.secrecy.filesystem.encryption.AES_ECB_Crypter.java

@Override
public void renameFile(File file, String newName) throws SecrecyCipherStreamException, FileNotFoundException {

    File parent = file.getParentFile();
    newName = FilenameUtils.removeExtension(newName);
    newName = Base64Coder.encodeString(newName);
    newName += "." + FilenameUtils.getExtension(file.getName());
    file.renameTo(new File(parent, newName));
}

From source file:io.fabric8.maven.plugin.mojo.infra.AbstractInstallMojo.java

private void moveFile(File tempFile, File destFile, String fileName) throws MojoExecutionException {
    if (!tempFile.renameTo(destFile)) {
        // lets try copy it instead as this could be an odd linux issue with renaming files
        try {/*  w w w. ja v a  2 s .co m*/
            IOHelpers.copy(new FileInputStream(tempFile), new FileOutputStream(destFile));
            log.info("Downloaded %s to %s", fileName, destFile);
        } catch (IOException e) {
            throw new MojoExecutionException(
                    "Failed to copy temporary file " + tempFile + " to " + destFile + ": " + e, e);
        }
    }
    if (!destFile.setExecutable(true)) {
        throw new MojoExecutionException("Cannot make " + destFile + " executable");
    }
}

From source file:ca.myewb.frame.PostParamWrapper.java

private File safeFileReplace(File file, DefaultFileItem item) throws Exception {

    File temp = new File(file.getPath() + file.getName() + ".tmp");

    //If the file exists, rename it .tmp
    if (file.exists()) {
        file.renameTo(temp);
        log.info("Old file renamed to " + file.getPath());
    }//from   w  w w . j a va  2s. co  m

    item.write(file); //write the file

    log.info("New file saved as " + file.getPath());

    //delete the temporary file
    if (temp.exists()) {
        temp.delete();
        log.info("Temporary file deleted from " + temp.getPath());
    }

    return file;
}

From source file:gtaps2.GTASAGUI.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

    //check user preferences
    if (jCheckBox1.isSelected()) {
        silent = true;//  www  .jav  a  2s.  c  om
    } else {
        silent = false;
    }
    if (jCheckBox2.isSelected()) {
        skygfx = true;
    } else {
        skygfx = false;
    }

    //backing up GTA:SA Files
    File bdir = new File(gamedir + "sa_backup");
    bdir.mkdir();

    File tmp = new File(gamedir + "gta-sa.exe");
    tmp.renameTo(new File(gamedir + "/sa_backup/gta-sa.exe"));
    tmp = new File(gamedir + "stream.ini");
    tmp.renameTo(new File(gamedir + "/sa_backup/stream.ini"));
    tmp = new File(gamedir + "vorbisFile.dll");
    tmp.renameTo(new File(gamedir + "/sa_backup/vorbisFile.dll"));

    //decompress data.zip with mods
    UnzipUtility zippr = new UnzipUtility();

    //if user just wants to install the full package
    if (skygfx == true && silent == true) {
        try {
            zippr.unzip("data.zip", gamedir);
        } catch (IOException e) {
            //exception handling
        }
    } else if (skygfx == true && silent == false) {
        bdir = new File(gamedir + "tmp");
        bdir.mkdir();

        try {
            zippr.unzip("data.zip", gamedir + "tmp");
        } catch (IOException e) {
            //exception handling
        }

        //move only skygfx files and clean up
        tmp = new File(gamedir + "tmp/stream.ini");
        tmp.renameTo(new File(gamedir + "stream.ini"));
        tmp = new File(gamedir + "tmp/skygfx.asi");
        tmp.renameTo(new File(gamedir + "skygfx.asi"));
        tmp = new File(gamedir + "tmp/skygfx1.ini");
        tmp.renameTo(new File(gamedir + "skygfx1.ini"));
        tmp = new File(gamedir + "tmp/skygfx2.ini");
        tmp.renameTo(new File(gamedir + "skygfx2.ini"));
        tmp = new File(gamedir + "tmp/skygfx3.ini");
        tmp.renameTo(new File(gamedir + "skygfx3.ini"));
        tmp = new File(gamedir + "tmp/gta-sa.exe");
        tmp.renameTo(new File(gamedir + "gta-sa.exe"));

        try {
            FileUtils.deleteDirectory(new File(gamedir + "tmp"));
        } catch (IOException e) {

        }

    } else {
        bdir = new File(gamedir + "tmp");
        bdir.mkdir();

        try {
            zippr.unzip("data.zip", gamedir + "tmp");
        } catch (IOException e) {
            //exception handling
        }

        //move only silent's files
        tmp = new File(gamedir + "tmp/SilentPatchSA.ini");
        tmp.renameTo(new File(gamedir + "SilentPatchSA.ini"));
        tmp = new File(gamedir + "tmp/SilentPatchSA.asi");
        tmp.renameTo(new File(gamedir + "SilentPatchSA.asi"));
        tmp = new File(gamedir + "tmp/vorbisFile.dll");
        tmp.renameTo(new File(gamedir + "vorbisFile.dll"));
        tmp = new File(gamedir + "tmp/vorbisHooked.dll");
        tmp.renameTo(new File(gamedir + "vorbisHooked.dll"));
        tmp = new File(gamedir + "tmp/gta-sa.exe");
        tmp.renameTo(new File(gamedir + "gta-sa.exe"));
        tmp = new File(gamedir + "tmp/script");
        tmp.renameTo(new File(gamedir + "script"));
        tmp = new File(gamedir + "tmp/advanced_plugin_management_example");
        tmp.renameTo(new File(gamedir + "advanced_plugin_management_example"));

        try {
            FileUtils.deleteDirectory(new File(gamedir + "tmp"));
        } catch (IOException e) {

        }
    }

    jOptionPane1.showMessageDialog(this, "Game patched!");

}