我正在尝试在文件夹之间移动单个文件。我使用file.renameTo()来移动我的文件。
@Url.Action(MVC.Home.Index())
在第一个//moving the file to new folder
//this is success
boolean fileMoveCompleted = finalFileToProcess
.renameTo(new File(processingFolderName
+ File.separator + finalFileToProcess.getName()));
//now trying to move the renamed file to another folder
//this is failing
fileMoveCompleted = finalFileToProcess
.renameTo(new File(successFolderName
+ File.separator
+ finalFileToProcess.getName()));
之后,文件路径仍然指向旧路径。有什么办法可以将同一个文件移动到另一个目录吗?
答案 0 :(得分:1)
您需要将renameTo的第一个目标文件保留为引用并重命名该文件。
File processing = new File(processingFolderName
+ File.separator
+ finalFileToProcess.getName());
boolean fileMoveCompleted = finalFileToProcess.renameTo(processing);
File finished = new File(successFolderName
+ File.separator
+ finalFileToProcess.getName());
fileMoveCompleted = processing.renameTo(finished);
但正如File.renameTo's JavaDoc所示,您最好使用Files.move。