开发者

How can I implement "recycle bin" functionality?

I am working on a Java desktop application in which I need to implement recycle bin functionality. Currently:

  1. I copy a file using my desktop application to a folder named recycle bin, and then delete the original file.
  2. I store the destination path in a text file, where the file was deleted, just to restore the file to the original location.
  3. While restoring the file, I just move tha开发者_运维百科t file to the original location.

My problem is that when a file with the same name is deleted from different locations, all the files moved to the Recycle Bin folder created by me and the old file with the same names are overwritten.


How can I sort out this issue? Also, is there any other alternate way to get functionality similar to recycle bin?


When you delete a file:

  1. Generate a random number.
  2. Check if a file with that name already exists or not in your bin. If yes, go to 1.
  3. Copy the file to the bin directory, but use the random number as the file name.
  4. Store the original file name and the random number in your text file.
  5. Delete the original.

(Note: this has issues if you have multiple applications/threads doing this at the same time.)

All the information you need to "restore" the file is in the text file, and you've avoided the duplicate name problem.

For more robustness against concurrent uses, and if you have Java 1.5 or greater, consider using a java.util.UUID rather than a "dumb" random number as the recycled file name. Can't be guaranteed to be safe AFAIK, but it should be good enough in most circumstances (especially if there's only one real user on the machine this is running).

Lastly, make sure you've closed your output streams in steps 3 and 4 above before you delete, and that they didn't throw any exception - otherwise you risk losing data. (Same thing when you restore: close the restored file stream before deleting the recycled one.)


Whenever there is need to move a file to recycle bin,

  1. Rename it with a key and store it in the recycle bin folder,
  2. Also map this key with the location of the file in your text file.

Now when user asks for restore, get the exact location from txt using the key and restore it.


The file name or the absolute file name "c.programs.file-to-be-deleted.xls" are not unique. what you want is the unique file ID which is generated for each files which need to stored along with the deleted file objects.

When the user tries to recyle/undelete the file from recycle bin, You will operate with the file id not the file name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜