Java File Rename renameFile(String oldPath, String newPath, boolean overwrite)

Here you can find the source of renameFile(String oldPath, String newPath, boolean overwrite)

Description

Rename a file from an old path to a new path.

License

Open Source License

Parameter

Parameter Description
oldPath original file path.
newPath destination path.
overwrite true to overwrite destination path if needed, false otherwise.

Exception

Parameter Description
IOException if an I/O exception occurred

Declaration

public static void renameFile(String oldPath, String newPath, boolean overwrite) throws IOException 

Method Source Code

//package com.java2s;

import java.io.File;

import java.io.IOException;

public class Main {
    /**//from   w ww .  j a v a  2s  . co  m
     * Rename a file from an old path to a new path.
     *
     * @param oldPath original file path.
     * @param newPath destination path.
     * @param overwrite true to overwrite destination path if needed, false otherwise.
     * @throws IOException if an I/O exception occurred
     */
    public static void renameFile(String oldPath, String newPath, boolean overwrite) throws IOException {

        boolean done = false;
        File source = new File(oldPath);
        File destination = new File(newPath);

        try {
            if (destination.exists()) {
                if (!overwrite) {
                    throw new IOException("'" + newPath + "' already exists");
                }
                if (!destination.delete()) {
                    throw new IOException("Could not delete '" + newPath + "'");
                }
            }

            if (!source.renameTo(destination)) {
                throw new IOException("'" + oldPath + "' could not be renamed to '" + newPath + "'");
            }
            done = true;
        } finally {
            if (done) {
                source.delete();
            }
        }
    }
}

Related

  1. renameFile(String oldname, String newname)
  2. renameFile(String oldname, String newname)
  3. renameFile(String oldname, String newone)
  4. renameFile(String oldPath, String newName)
  5. renameFile(String oldPath, String newPath)
  6. renameFile(String origPath, String destPath)
  7. renameFile(String path, String newPath)