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?
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.
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.
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.
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 .
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));
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With