How can I implement “recycle bin” functionality?

前端 未结 3 1472
无人及你
无人及你 2021-01-18 15:00

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 f
3条回答
  •  清歌不尽
    2021-01-18 15:17

    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.)

提交回复
热议问题