Don*_*gyi 12
我使用以下方法:
public static void rename(String oldFileName, String newFileName) {
new File(newFileName).delete();
File oldFile = new File(oldFileName);
oldFile.renameTo(new File(newFileName));
}
Run Code Online (Sandbox Code Playgroud)
我已经完成了编写自己的方法,对于每个对可能的解决方案感兴趣的人,我使用了ApacheCommons FileUtils,这也许并不完美,但对我来说效果还不错:
/**
* 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;
}
}
Run Code Online (Sandbox Code Playgroud)
可以使用预删除目标来实现具有重写方法的纯 Java nio 解决方案,如图所示
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);
}
Run Code Online (Sandbox Code Playgroud)
Apache FileUtils JavaDoc for FileUtils.copyFileToDirectory说,"如果目标文件存在,那么这个方法将覆盖它." 复制后,您可以在删除之前进行验证.
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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
33275 次 |
最近记录: |