Here you can find the source of renameFile(String oldPath, String newPath, boolean overwrite)
Parameter | Description |
---|---|
oldPath | original file path. |
newPath | destination path. |
overwrite | true to overwrite destination path if needed, false otherwise. |
Parameter | Description |
---|---|
IOException | if an I/O exception occurred |
public static void renameFile(String oldPath, String newPath, boolean overwrite) throws IOException
//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(); } } } }