So, your servlet uploaded a file and stored it on your server's file system? And now it tries to rename the file on your server's file system and it fails? No... you said the file hadn't been persisted anywhere, so probably that's not it.
Or were you expecting to rename a file on the client? You certainly can't do that from the server.
I think your question needs a little more clarification, if those guesses didn't answer it.
I have uploaded the file using a Struts 2 action. The framework automatically places a reference to the uploaded in the action property whose name matches <s:file name="image" label="Picture"/>, so I have:
private File image = null;
in my action with the appropriate getter and setter, of course.
I have not called createNewFile() or saved the object to any filesystem (Whether the file was saved in a temporary directory by the servlet container I don't know). It would just be as if I simply created a File object using:
and immediately wanted to rename it on the next line. Now calling
and then calling
Mind you that new File("newfilename.png") does not exist as an actual file, it just is the name I want associated with my File object.
No other processes have a handle on the file being uploaded and I have the rights to rename the file (but that shouldn't matter anyway since the file is in memory).
Completely relying on File.renameTo is not a good idea if you ask to me, as an example remember that it always fails (hence returning false) if you're trying to move the file from a physical drive to another one, no matter if you got the rights to do it on both the drives. On our production servlet we went with something like this :
Where physicalCopy is something like
This way, you can get profit from the faster renameTo operation, and if it fails somehow you can still get your file renamed wherever you want (as long as you've the rights to do it).
John Eric Hamacher
Joined: Apr 25, 2007
Thank you, Matteo. I ended up doing a similar thing by using the Commons IO FileUtils.copyFile(File, File).