我正在尝试使用 java 中的 renameTo() 将文件从一个目录移动到另一个目录,但是 renameTo 不起作用(不重命名和移动文件)。基本上,我想先删除一个具有相同文件名的文件,然后将文件从另一个目录复制到我最初删除文件的相同位置,然后复制具有相同名称的新文件。
//filePath = location of original file with file name appended. ex: C:\Dir\file.txt
//tempPath = Location of file that I want to replace it to file file without the file name. ex: C:\AnotherDir
int pos = filePath.indexOf("C:\\Dir\\file.txt");
//Parse out only the path, so just C:\\Dir
String newFilePath = filePath.substring(0,pos-1);
//I want to delete the original file
File deletefile = new File(newFilePath,"file.txt");
if (deletefile.exists()) {
success = deletefile.delete();
}
//There is file already exists in the directory, but I am just appending .tmp at the end
File newFile = new File(tempPath + "file.txt" + ".tmp");
//Create original file again with same name.
File oldFile = new File(newFilePath, "file.txt");
success = oldFile.renameTo(newFile); // This doesnt work.
你能告诉我我做错了什么吗?
谢谢你的帮助。