且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何实现“回收站"?功能?

更新时间:2023-02-14 13:21:57

删除文件时:

  1. 生成一个随机数.
  2. 检查bin中是否已经存在具有该名称的文件.是,执行1.
  3. 将文件复制到bin目录,但使用随机数作为文件名.
  4. 将原始文件名和随机数存储在文本文件中.
  5. 删除原件.

(注意:如果您有多个应用程序/线程同时执行此操作,则会出现问题.)

您需要恢复"文件的所有信息都在文本文件中,并且避免了名称重复的问题.

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

要获得更强的并发使用性,并且如果您使用Java 1.5或更高版本,请考虑使用

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

最后,请确保在删除之前已关闭上述第3步和第4步中的输出流,并且它们没有引发任何异常-否则,您可能会丢失数据.(还原时也是如此:在删除回收的文件流之前,先关闭还原的文件流.)

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