Java Rename File renameFile(File src, File dest)

Here you can find the source of renameFile(File src, File dest)

Description

Rename a file.

License

Open Source License

Parameter

Parameter Description
src the existing file to rename
dest the target name for the file

Exception

Parameter Description
IOException if the rename operation does not succeed.

Declaration

public static void renameFile(File src, File dest) throws IOException 

Method Source Code

//package com.java2s;
// modify it under the terms of the GNU General Public License

import java.io.File;

import java.io.IOException;

public class Main {
    /** Rename a file./*from  www .ja  v a2  s.c om*/
     * 
     * The File.renameTo method can silently fail and simply return false.
     * This method will retry the operation several times until it succeeds,
     * or will throw an exception if the rename was unsuccessful.
     * 
     * @param src the existing file to rename
     * @param dest the target name for the file
     * @throws IOException if the rename operation does not succeed.
     */
    public static void renameFile(File src, File dest) throws IOException {
        if (dest.exists())
            dest.delete();

        boolean success = false;
        for (int i = 0; i < 10; i++) {
            try {
                if (i > 0)
                    Thread.sleep(500);
            } catch (InterruptedException e) {
            }

            if (src.renameTo(dest)) {
                success = true;
                break;
            }
        }

        // if the src and dest files are located across a slow network, the
        // rename might have completed successfully, but queries against the
        // target filename might still fail for a second or two.  Doublecheck
        // to ensure that the file is accessible in the dest location.
        if (success) {
            for (int i = 0; i < 10; i++) {
                try {
                    if (i > 0)
                        Thread.sleep(500);
                } catch (InterruptedException e) {
                }

                if (dest.exists())
                    return;
            }
        }

        throw new IOException("Could not rename '" + src + "' to '" + dest + "'");
    }
}

Related

  1. renameDirectory(File fromDir, File toDir)
  2. renameDirectory(String in_currentDirectoryPath, String in_newDirectoryPath)
  3. renameDirectory(String newDir, String oldDir)
  4. renameExcludedFiles(File existingBinaryFolder, Collection excludedBids)
  5. renameExistingWithRetries(final File fromFile, final File toFile)
  6. renameFile(String source, String dest)
  7. renameFile(String sourcePath, String targetPath)
  8. renameFile(String src_pathname, String dest_pathname)
  9. renameFileFromChinese(File file)