Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an operation to move and overwrite files?

Tags:

java

io

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?

like image 307
Robin Avatar asked Jan 18 '13 13:01

Robin


People also ask

Does Move command overwrite files?

Attention: The mv (move) command can overwrite many existing files unless you specify the -i flag. The -i flag prompts you to confirm before it overwrites a file. If both the -f and -i flags are specified in combination, the last flag specified takes precedence.

How do I overwrite an existing file?

Save As -> Replace File If you are accustomed to selecting "File -> Save As" when saving documents, you can also overwrite the file with your changes this way. Select "Replace File. This is the same behavior as File Save." The original file will be overwritten.

How do I overwrite a file in Windows?

Right-click the document file the content of which you want to replace. Press the Alt key and select Operations > Replace with File... from the menu bar. Locate and select the file that you want to use for replacing the original file content. Click OK.

Does Shutil move overwrite?

How do I overwrite a file in Shutil? Use shutil. move() to overwrite a file in Python Call shutil. move(src, dst) with src and dst as full file paths to move the file at src to the destination dst .


2 Answers

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));
}
like image 60
Donato Szilagyi Avatar answered Sep 20 '22 18:09

Donato Szilagyi


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;
}
like image 24
Abu Sulaiman Avatar answered Sep 17 '22 18:09

Abu Sulaiman