是否有移动和覆盖文件的操作? [英] Is there an operation to move and overwrite files?
问题描述
我正在寻找移动和覆盖文件的操作。我知道 Java7 ,但我希望绕过Java7。我也知道 FileUtils 和 Guava ,但FileUtils不会覆盖,而Guava也不会记录它。
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.
你有什么建议吗?
推荐答案
我已经完成了编写自己的方法,对于每个对可能的解决方案感兴趣的人,我使用了ApacheCommons FileUtils,这也许并不完美,但对我来说效果还不错:
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;
}
}
这篇关于是否有移动和覆盖文件的操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!