Is there an operation to move and overwrite files?
Asked Answered
F

11

14

I am looking for an operation to move and overwrite a File. I know that there is a new Method in Java7, but I was hoping to get around Java7. Also I know about the Methods in FileUtils and Guava, but the FileUtils won't overwrite and the Guava one does not document it.

Also I am aware, I could write my own Method, well I started, but saw some Problems here and there, so I was hoping for something already done.

Do you have any suggestions?

Fabozzi answered 18/1, 2013 at 13:32 Comment(2)
Have you actually tried with Guava?Boyse
@Boyse No I didn't tried the Guava one. But I states to Implement the Unix mv, and the mv won't overwrite without prompt. unixhelp.ed.ac.uk/CGI/man-cgi?mvFabozzi
F
6

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;
    }
}
Fabozzi answered 18/1, 2013 at 14:14 Comment(2)
What is CSVUtils?Ageratum
The name of that class. These are static methods.Fabozzi
E
12

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));
}
Earwitness answered 18/1, 2013 at 13:35 Comment(2)
Thank you, well this was my first implementation, but my files are quite large. So if the Programm will break after you will delete the firstFile, all your data is lost or spread somewhere. Edit: And this Problem appeared, this is why I am asking. So I need to fix this.Fabozzi
I realize this is an old post, but I am currently using this method and it does not overwrite as the author requested, which is also why I'm replacing itAnyhow
C
7

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;
}
Callimachus answered 13/5, 2015 at 14:3 Comment(0)
F
6

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;
    }
}
Fabozzi answered 18/1, 2013 at 14:14 Comment(2)
What is CSVUtils?Ageratum
The name of that class. These are static methods.Fabozzi
I
5

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);
}
Ithaman answered 28/1, 2015 at 23:30 Comment(0)
G
3

shortest solution which worked for me :

File destFile = new File(destDir, file.getName());
if(destFile.exists()) {
    destFile.delete();
}
FileUtils.moveFileToDirectory(file, destDir, true);
Godgiven answered 28/2, 2017 at 4:1 Comment(1)
It's the same as what the author said above. He can't delete before moving the file :(Midtown
C
2

Guava Files.write:

Overwrites a file with the contents of a byte array

Files.write(bytes, new File(path));

Files.copy:

Warning: If to represents an existing file, that file will be overwritten with the contents of from. If to and from refer to the same file, the contents of that file will be deleted.

Files.move uses copy under the hood. So its safe to assume it overwrites too.

Cronyism answered 30/6, 2017 at 15:53 Comment(0)
V
1

In case you will proceed writing your own utility, you may want to take a look at implementation of the copy task in Ant since it supports overwriting.

Vulgarity answered 18/1, 2013 at 13:40 Comment(1)
Thank you for the link, but I was hoping for a existing solutions.Fabozzi
O
1

Using Apache Commons FileUtils :

  try {         
        FileUtils.moveFile(source, dest);
        print("------------------------------");
        print(name
                + " moved to "
                + PropertiesUtil
                        .getProperty(PropertiesUtil.COMPLETED_PATH));

    } catch (FileExistsException fe){

        if(dest.delete()){
            try {
                FileUtils.moveFile(source, dest);
            } catch (IOException e) {
                logger.error(e);
            }
            print("------------------------------");
            print(name
                    + " moved to "
                    + PropertiesUtil
                            .getProperty(PropertiesUtil.COMPLETED_PATH));
        }
    } catch (Exception e) {

        logger.error(e);
    }
Organist answered 8/8, 2014 at 6:29 Comment(0)
F
0

You could also use Tools Like https://xadisk.java.net/ to enable transactional access to existing file systems.

There is also an alternative from apache:

https://commons.apache.org/proper/commons-transaction/apidocs/org/apache/commons/transaction/file/FileResourceManager.html

Fruiter answered 26/2, 2016 at 10:4 Comment(0)
A
0
Files.deleteIfExists(destinationPath);
Files.move(fileToMove, destinationPath);
Apomixis answered 8/6, 2023 at 15:33 Comment(0)
P
0

Updated on 2024/06/22:

It would be more elegant.

Doc: StandardCopyOption.REPLACE_EXISTING

FileUtils.copyFile(oldFile,newFile,StandardCopyOption.REPLACE_EXISTING)
FileUtils.forceDelete(oldFile)
Packton answered 21/6 at 18:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.