Is there an operation to move and overwrite files?

I use the following method:

public static void rename(String oldFileName, String newFileName) {
    new File(newFileName).delete();
    File oldFile = new File(oldFileName);
    oldFile.renameTo(new File(newFileName));
}

I am finished with writing my own Method, for everybody interested in a possible solution, I used the ApacheCommons FileUtils, also this is probably not perfect, but works well enough for me:

/**
 * Will move the source File to the destination File.
 * The Method will backup the dest File, copy source to
 * dest, and then will delete the source and the backup.
 * 
 * @param source
 *            File to be moved
 * @param dest
 *            File to be overwritten (does not matter if
 *            non existent)
 * @throws IOException
 */
public static void moveAndOverwrite(File source, File dest) throws IOException {
    // Backup the src
    File backup = CSVUtils.getNonExistingTempFile(dest);
    FileUtils.copyFile(dest, backup);
    FileUtils.copyFile(source, dest);
    if (!source.delete()) {
        throw new IOException("Failed to delete " + source.getName());
    }
    if (!backup.delete()) {
        throw new IOException("Failed to delete " + backup.getName());
    }
}

/**
 * Recursive Method to generate a FileName in the same
 * Folder as the {@code inputFile}, that is not existing
 * and ends with {@code _temp}.
 * 
 * @param inputFile
 *            The FileBase to generate a Tempfile
 * @return A non existing File
 */
public static File getNonExistingTempFile(File inputFile) {
    File tempFile = new File(inputFile.getParentFile(), inputFile.getName() + "_temp");
    if (tempFile.exists()) {
        return CSVUtils.getNonExistingTempFile(tempFile);
    } else {
        return tempFile;
    }
}

A pure Java nio solution move with overriding method could be implemented with a pre-delete target as shown

public void move(File sourceFile, String targetFileName) {
    Path sourcePath = sourceFile.toPath();
    Path targetPath = Paths.get(targetFileName);
    File file = targetFile.toFile();
    if(file.isFile()){
        Files.delete(targetPath);
    }
    Files.move(sourcePath, targetPath);
}

Apache FileUtils JavaDoc for FileUtils.copyFileToDirectory says, "If the destination file exists, then this method will overwrite it." After the copy, you could verify before deleting.

public boolean moveFile(File origfile, File destfile)
{
    boolean fileMoved = false;
    try{
    FileUtils.copyFileToDirectory(origfile,new File(destfile.getParent()),true);
    File newfile = new File(destfile.getParent() + File.separator + origfile.getName());
    if(newfile.exists() && FileUtils.contentEqualsIgnoreCaseEOL(origfile,newfile,"UTF-8"))
    {
        origfile.delete();
        fileMoved = true;
    }
    else
    {
        System.out.println("File fail to move successfully!");
    }
    }catch(Exception e){System.out.println(e);}
    return fileMoved;
}

Tags:

Java

Io