删除目录中最旧的文件,直到其文件大小低于特定大小
我想要完成的任务如下:假设我有一个将图像写入文件目录(SD 或内部缓存)的函数。写出文件后,我执行检查以查看我的图像目录是否在特定的总文件大小之内(现在,我正在使用此 函数递归计算目录文件 尺寸)。如果我刚刚添加的文件使该目录太大,那么我想要做的就是继续删除旧文件,直到我们刚好低于最大文件大小。
我正在考虑首先对文件目录成员从最旧的开始进行排序(通过比较器,使用此 示例),然后将数组转换为ArrayList以获取其Iterator,那么当我们的目录文件大小为仍然高于最大文件大小,并且我仍然有要迭代的文件,我删除旧文件,直到跳出 while 循环。有没有更有效的方法来实现这一目标?
What I'm trying to accomplish is the following: Suppose I have a function that writes an image to a File directory (either SD or internal cache). After writing out the File, I perform a check to see if my image directory is within a certain total file size (right now, I'm using this function to recursively calculate the directory's file size). If the file that I just added makes that directory too big, then what I want to do is keep deleting older files until we are just below that max file size.
I was thinking of first sorting the File directory members from oldest first (via comparator, ascending order using this example), then convert the array into an ArrayList to get its Iterator, then while our directory file size is still above the max file size, and I still have files to iterate to, I delete the older files until I break out of that while loop. Is there a more efficient way of accomplishing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的瓶颈很可能是文件系统操作(即:读取目录内容和删除文件),而不是内存中的操作,因此您可能不应该太担心后者的效率,只要您不要做一些效率极低的事情。
您描述的粗略算法听起来不错。您可以通过简单地执行以下操作来避免 ArrayList 转换:
Your bottleneck is most likely going to be file system operations (ie: reading the directory contents and deleting the files), not the in-memory manipulation, so you probably shouldn't worry too much about the efficiency of the latter so long as you don't do something grossly inefficient.
The rough algorithm you describe sounds fine. You can avoid the ArrayList conversion by simply doing something like: