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:de.thischwa.pmcms.gui.listener.ListenerEditPersistentPojoProperties.java

private void edit(Shell shell, Gallery gallery) {
    String oldGalleryName = gallery.getName();
    File gallerySrc = PoPathInfo.getSiteGalleryDirectory(gallery);
    if (DialogManager.startDialogPersitentPojo(shell, gallery)) {
        if (!oldGalleryName.equals(gallery.getName())) {
            Site site = PoInfo.getSite(gallery);
            File galleryDest = PoPathInfo.getSiteGalleryDirectory(gallery);
            gallerySrc.renameTo(galleryDest);
            File cacheSrc = new File(PoPathInfo.getSiteImageCacheDirectory(site), oldGalleryName);
            if (cacheSrc.exists()) {
                File cacheDest = new File(PoPathInfo.getSiteImageCacheDirectory(site), gallery.getName());
                cacheSrc.renameTo(cacheDest);
            }/*  w  ww .j a v a 2 s. c  o  m*/
            logger.debug("Gallery got a new name, dependent directories are renamed!");
        }
        actionAfterChangedProperties(gallery);
        logger.debug("Properties of a gallery are changed!");
    }
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.localworkspace.LocalMetadataTable.java

/**
 * Helper method to avoid a known Java File.renameTo issue on Windows.
 * File.renameTo appears to intermittently fail on Windows. We retry a few
 * times after sleeping briefly. A day long experiment shows that in a
 * scenario where renameTo is known to have intermittent failures, that we
 * retry at most once, at which point it succeeds. The scenario where rename
 * has failed is when renaming the slot 2 file to slot 1 in the positionFile
 * method (note, we've never seen rename fail in the recover methods which
 * also does a rename of slot 2 to slot 1).
 *
 * Interesting notes to consider - we've never seen renameTo fail when
 * renaming slot 3 to slot 2. The slot 2 file is never opened for read or
 * write. The slot 1 file is only ever opened for READ. The slot 3 file is
 * only ever opened for WRITE. SEE TEE.TFSPREVIEW BUG 4184 for more info.
 *
 *
 * @param source/*from w w  w.j  a  v  a 2  s  .  c  o m*/
 * @param destination
 */
private void renameFile(final File source, final File destination) {
    for (int i = 0; i < 5; i++) {
        if (source.renameTo(destination)) {
            return;
        }

        try {
            log.info("RETRY rename [" + i + "]"); //$NON-NLS-1$ //$NON-NLS-2$
            Thread.sleep(100);
        } catch (final InterruptedException e) {
        }
    }

    throw new RuntimeException(MessageFormat.format("Could not rename {0} to {1} in recover", source.getName(), //$NON-NLS-1$
            destination.getName()));
}

From source file:org.shareok.data.ouhistory.OuHistoryJournalDataProcessorImpl.java

@Override
public String processSafpackage() {
    try {/*w w w.j  a  va2s  .co  m*/
        String csvPath = journalData.getFilePath();
        String extension = DocumentProcessorUtil.getFileExtension(journalData.getFilePath());
        if (null == extension || !extension.contains("csv")) {
            throw new NonCsvFileException("The uploaded file is not a CSV file!");
        }
        SAFPackage safPackageInstance = new SAFPackage();
        safPackageInstance.processMetaPack(csvPath, true);
        String csvDirectoryPath = DocumentProcessorUtil.getFileContainerPath(csvPath);
        File csv = new File(csvPath);
        File safPackage = new File(csvDirectoryPath + File.separator + "SimpleArchiveFormat.zip");
        File newPackage = null;
        if (safPackage.exists()) {
            newPackage = new File(csvDirectoryPath + File.separator
                    + DocumentProcessorUtil.getFileNameWithoutExtension(csv.getName()) + ".zip");
            if (!newPackage.exists()) {
                safPackage.renameTo(newPackage);
            } else {
                throw new FileAlreadyExistsException("The zip file of the SAF package already exists!");
            }
        }
        File safPackageFolder = new File(csvDirectoryPath + File.separator + "SimpleArchiveFormat");
        if (safPackageFolder.exists()) {
            FileUtils.deleteDirectory(safPackageFolder);
        }
        return (null == newPackage) ? null : newPackage.getAbsolutePath();

    } catch (IOException | FileAlreadyExistsException | NonCsvFileException ex) {
        logger.error(ex.getMessage());
    }
    return null;
}

From source file:com.thoughtworks.studios.shine.cruise.stage.details.StageStorage.java

public void save(Graph graph) {
    StageIdentifier identifier = extractStageIdentifier(graph);

    if (isStageStored(identifier)) {
        return;/*from ww  w. j a v a 2 s  .  c o m*/
    }

    synchronized (stageKey(identifier)) {
        if (isStageStored(identifier)) {
            return;
        }

        File file = new File(tmpStagePath(identifier));

        file.getParentFile().mkdirs();
        try {
            OutputStream os = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(file)));
            graph.persistToTurtle(os);
            os.flush();
            os.close();
            file.renameTo(new File(stagePath(identifier)));
        } catch (IOException e) {
            throw new ShineRuntimeException(e);
        } finally {
            file.delete();
        }
    }
}

From source file:com.flipkart.aesop.runtime.impl.admin.RuntimeConfigServiceImpl.java

/**
 * Restores the previous config file, if found
 * @param runtimeName name of the runtime
 *//*from ww w  . jav  a  2s.  c  o  m*/
private void restorePrevConfigFile(String runtimeName) {
    File configFile = null;
    try {
        configFile = this.getRuntimeConfig(runtimeName).getFile();
    } catch (IOException e) {
        LOGGER.error("IOException while getting runtime config file", e);
    }
    if (configFile.exists()) {
        configFile.delete();
    }
    File prevFile = new File(configFile.getParent() + "/" + RuntimeConfigServiceImpl.PREV_RUNTIME_FILE_PREFIX
            + configFile.getName());
    ;
    if (prevFile.exists()) {
        prevFile.renameTo(configFile);
    }
}

From source file:jetbrains.exodus.entitystore.FileSystemBlobVaultOld.java

public void setContent(final long blobHandle, @NotNull final File file) throws Exception {
    final File location = getBlobLocation(blobHandle, false);
    if (!file.renameTo(location)) {
        try (FileInputStream content = new FileInputStream(file)) {
            setContentImpl(content, location);
        }/*from w  w  w. j  a v a2s .  c o m*/
    }
    if (size.get() != UNKNOWN_SIZE) {
        size.addAndGet(IOUtil.getAdjustedFileLength(location));
    }
}

From source file:com.bluedragon.platform.java.JavaFileIO.java

private void rolloverLogFile(File logFile) {
    // delete the oldest (10th) backup; increment the numbers of the remaining backups
    for (int backupNo = 10; backupNo > 0; backupNo--) {
        File backupFile = new File(logFile + "." + backupNo);
        if (backupFile.exists()) {
            if (backupNo == 10) {
                backupFile.delete();//from www.  j ava  2  s.c  o m
            } else {
                backupFile.renameTo(new File(logFile + "." + (backupNo + 1)));
            }
        }
    }

    if (logFile.exists()) {
        // Try 3 times to rename bluedragon.log, sleeping 500ms between each attempt.
        int numAttempts = 0;
        while ((numAttempts < 3) && !logFile.renameTo(new File(logFile + ".1"))) {
            numAttempts++;
            try {
                Thread.sleep(500);
            } catch (InterruptedException ignore) {
            }
        }
    }
}

From source file:com.buaa.cfs.utils.FileUtil.java

/**
 * Move the src file to the name specified by target.
 *
 * @param src    the source file/*  w w w  . j a  va  2 s.co m*/
 * @param target the target file
 *
 * @throws IOException If this operation fails
 */
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);
        }
    }
}

From source file:JarEntryOutputStream.java

/**
 * Utility method used to swap the underlying jar file out for the new one.
 * This method closes the old jar file, deletes it, moves the new jar
 * file to the location where the old one used to be and opens it.
 * <p>//from w  w w.j a  v  a2s.c om
 * This is used when modifying the jar (removal, addition, or changes
 * of entries)
 *
 * @param newJarFile the file object pointing to the new jar file
 */
void swapJars(File newJarFile) throws IOException {
    File oldJarFile = new File(getName());
    this.jar.close();
    oldJarFile.delete();
    if (newJarFile.renameTo(oldJarFile)) {
        this.jar = new JarFile(oldJarFile);
    } else {
        throw new IOException();
    }
}

From source file:org.kew.rmf.matchconf.ConfigurationEngine.java

/**
 * Writes the configuration to the file system. Takes care not to overwrite existing configs,
 * complains in a nice way about not existing input and output files.
 *
 * @throws Exception/*from w w  w.  j ava2  s .c o  m*/
 */
public void write_to_filesystem() throws Exception {
    // Perform a few checks:
    // 1. does the working directory exist?
    File workDir = new File(this.config.getWorkDirPath());
    if (!workDir.exists()) {
        throw new FileNotFoundException(String.format(
                "The specified working directory %s does not exist! You need to create it and put the query file in it.",
                config.getWorkDirPath()));
    }
    // 2a. does the query file exist?
    File queryFile = new File(workDir, config.getQueryFileName());
    if (!queryFile.exists()) {
        throw new FileNotFoundException(String.format(
                "There is no file found at the specified location of the query-file %s. Move the query file there with the specified queryFileName.",
                queryFile.toPath()));
    }
    // 2b. if the config is for matching: does the authority file exist?
    if (this.config.getClassName().equals("MatchConfiguration")) {
        File authorityFile = new File(workDir, config.getAuthorityFileName());
        if (!authorityFile.exists()) {
            throw new FileNotFoundException(String.format(
                    "There is no file found at the specified location of the authority-file %s. Move the authority file there with the specified authorityFileName.",
                    authorityFile.toPath()));
        }
    }
    // 3. write out the xml-configuration file
    File configFile = new File(workDir, "config_" + config.getName() + ".xml");
    if (configFile.exists()) {
        // rename existing config file and save new one under the actual name
        configFile.renameTo(new File(configFile.toString() + "_older_than_"
                + DateTimeFormat.forPattern("yyyy-MM-dd_HH-mm-ss").print(new DateTime())));
        configFile = new File(workDir, "config_" + config.getName() + ".xml");
    }
    try (BufferedWriter br = new BufferedWriter(new FileWriter(configFile))) {
        br.write(StringUtils.join(this.toXML(), System.getProperty("line.separator")));
    }
}