Reputation: 3840
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?
Upvotes: 14
Views: 51711
Reputation:
Updated on 2024/06/22:
It would be more elegant.
Doc: StandardCopyOption.REPLACE_EXISTING
FileUtils.copyFile(oldFile,newFile,StandardCopyOption.REPLACE_EXISTING)
FileUtils.forceDelete(oldFile)
Upvotes: 0
Reputation: 939
Files.deleteIfExists(destinationPath);
Files.move(fileToMove, destinationPath);
Upvotes: 0
Reputation: 1202
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);
}
Upvotes: 5
Reputation: 26180
Overwrites a file with the contents of a byte array
Files.write(bytes, new File(path));
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.
Upvotes: 2
Reputation: 31
shortest solution which worked for me :
File destFile = new File(destDir, file.getName());
if(destFile.exists()) {
destFile.delete();
}
FileUtils.moveFileToDirectory(file, destDir, true);
Upvotes: 3
Reputation: 1804
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:
Upvotes: 0
Reputation: 1507
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;
}
Upvotes: 7
Reputation: 448
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);
}
Upvotes: 1
Reputation: 4369
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));
}
Upvotes: 12
Reputation: 3840
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;
}
}
Upvotes: 6
Reputation: 804
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.
Upvotes: 1