我如何实现“回收站"?功能? [英] How can I implement "recycle bin" functionality?

查看:95
本文介绍了我如何实现“回收站"?功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Java桌面应用程序,在其中我需要实现回收站功能.当前:

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

  1. 我使用桌面应用程序将文件复制到名为回收站的文件夹,然后删除原始文件.
  2. 我将目标路径存储在一个文本文件中,该文件已被删除,只是为了将文件还原到原始位置.
  3. 还原文件时,我只是将文件移到原始位置.

我的问题是,当从不同位置删除具有相同名称的文件时,所有移动到由我创建的回收站文件夹和具有相同名称的旧文件的文件都将被覆盖.

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?

推荐答案

删除文件时:

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

这篇关于我如何实现“回收站"?功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆