我已经在我的应用程序中实现了离线缓存,为此我将图像存储在外部存储中。我希望一旦我的缓存图像文件夹限制达到30,那么它就开始用新的图像替换旧图像。为此我删除后实现了算法 -
public static boolean deleteDir(File dir)
{
if (dir != null && dir.isDirectory())
{
String[] children = dir.list();
if(children.length>30)
{
int exceed=children.length-30;
for (int i = 0; i <exceed; i++)
{
boolean success = deleteDir(new File(dir, children[i]));
if (!success)
{
return false;
}
else
{
Log.e("deleted","file deleted");
}
}
}
}
return dir.delete();
}
但是上面的算法没有按预期工作。它可能会删除新添加的图像。我也尝试在下面算法实现。但它也没有按预期工作。我不明白我哪里出错。< / p>
public static boolean deleteDir(File dir)
{
if (dir != null && dir.isDirectory())
{
String[] children = dir.list();
if(children.length>30)
{
int exceed=children.length-30;
int destroy=(children.length-exceed)-1;
for (int i = children.length; i >destroy; i--)
{
boolean success = deleteDir(new File(dir, children[i]));
if (!success)
{
return false;
}
else
{
Log.e("deleted","file deleted");
}
}
}
}
return dir.delete();
}
答案 0 :(得分:0)
试试这个
public static void deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
File[] files = dir.listFiles();
if (files.length > 30) {
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
if (o1.lastModified() > o2.lastModified()) {
return 1;
} else if (o1.lastModified() < o2.lastModified()) {
return -1;
}
return 0;
}
});
for (int i = 0; i < files.length - 30; i++) {
files[i].delete();
}
}
}
}