简体   繁体   中英

Attempting to rename a File in Java does not work (using java.io.File.renameTo method)

I have a method where I load a file, do some changes, and then save it again. However, as insurance against exceptions during saving I create a new File and save to that one first (since improperly formated data can cause an Exception in the middle of saving). Once the saving is complete I delete the original file and rename the new one to have the original's name.

Code looks essentially like this:

MyDataClass.save(tempfile);
originalfile.delete();
tempfile.renameTo(originalfile);

The issue is that the call to the renameTo method always returns 'false' and the new file (tempfile) remains with the random name it was created with (the original file deleted). 删除)。

Anyone have a guess as to why the renaming fails?

I guess this may be because of the program unable to check the recent status of the file deletion. You can debug this by trying out the following code:

MyDataClass.save(tempfile);
if(originalfile.delete()==true){
tempfile.renameTo(originalfile);
}
else{
System.out.println("File is not deleted");
}

Or you can try this.

MyDataClass.save(tempfile);
originalfile.delete();
Thread.sleep(4000);//Make the thread sleep so that the recent status can be detected
tempfile.renameTo(originalfile);

Also, I see that you have used MyDataClass.save to save the file. Please check if you closed the file after saving.

If the file is locked when you tried to rename, it might not have worked

Also, if you are using windows explorer to view your files, you might want to refresh to see the recent file created

See Files.move for the newer classes Path, Paths, and Files.

MyDataClass.save(tempfile);
Files.move(tempfile.toPath(), originalfile.toPath(),
    StandardCopyOption.REPLACE_EXISTING,
    StandardCopyOption.ATOMIC_MOVE);

This of course assumes that save closed the tempfile correctly.

I have finally found out the issue. The thing is, I was using the Apache POI (Microsoft Excel Library) and it wouldn't save updates like it should. Trying to save to the existing file caused exceptions, so I thought I'd save to a second file and then delete the original/rename the new one. Turns out, however, that the very act of saving it to a new file also causes it to save to the original file!! So I just have to save to a temporary file and then delete it...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM