Java Rename File renameOverwrite(String oldname, String newname)

Here you can find the source of renameOverwrite(String oldname, String newname)

Description

Rename the file with oldname to newname.

License

Apache License

Declaration

static public void renameOverwrite(String oldname, String newname) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    /**//from  www .  ja  v  a2s  .co  m
     * Rename the file with oldname to newname. If a file with oldname does not
     * exist, nothing occurs. If a file with newname already exists, it is
     * deleted it before the renaming operation proceeds. */
    static public void renameOverwrite(String oldname, String newname) throws IOException {
        try {
            if (exists(oldname)) {
                delete(newname);
                File file = new File(oldname);
                file.renameTo(new File(newname));
            }
        } catch (Throwable e) {
            throw toIOException(e);
        }
    }

    /**
     * Return true or false based on whether the named file exists. */
    static public boolean exists(String filename) throws IOException {
        try {
            return (new File(filename)).exists();
        } catch (Throwable e) {
            throw toIOException(e);
        }
    }

    /**
     * Delete the named file
     */
    public static void delete(String filename) throws IOException {
        try {
            (new File(filename)).delete();
        } catch (Throwable e) {
            throw toIOException(e);
        }
    }

    /**
     * Deletes the given file <code>aFile</code>.
     *
     * @param  aFile The file to be deleted.
     * @throws IOException if the the deletion was not successful.
     */
    public static void delete(File aFile) throws IOException {
        if (aFile.exists()) {
            if (!aFile.delete()) {
                throw new IOException("Failed to delete " + aFile);
            }
        }
    }

    static IOException toIOException(Throwable e) {
        if (e instanceof IOException) {
            return (IOException) e;
        } else {
            return new IOException(e.getMessage());
        }
    }
}

Related

  1. renameFiles(File fileDirectory, String regex, String replacement)
  2. renameFiles(String rootDir, String sourcePostfix, String destPostfix)
  3. renameFolder(String destinationFolderPath, String zipFileName, String prefix)
  4. renameLocal(String oldPath, String newPath)
  5. renameOldFile(final String fileName)
  6. renameSuffix(File f, String suffix)
  7. renameTempDMLScript(String dmlScriptFile)
  8. renameTo(File currentFile, String newName)
  9. renameTo(File from, File to, boolean deleteDestination)