限制后从外部存储中删除旧图像
Deleting older images from external storage after a limit
我已经在我的应用程序中实现了离线缓存,为此我将图像存储在外部 storage.I 希望一旦我的缓存图像文件夹限制达到 30 然后它开始用新图像替换旧图像 ones.For 我实现了以下删除算法-
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();
}
但是上面的算法不起作用,因为 expected.It 可能会删除新添加的 images.I 也尝试在 algorithm.But 下面实现它也不起作用,因为 expected.I 失败了明白我哪里错了。
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();
}
试试这个
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();
}
}
}
}
我已经在我的应用程序中实现了离线缓存,为此我将图像存储在外部 storage.I 希望一旦我的缓存图像文件夹限制达到 30 然后它开始用新图像替换旧图像 ones.For 我实现了以下删除算法-
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();
}
但是上面的算法不起作用,因为 expected.It 可能会删除新添加的 images.I 也尝试在 algorithm.But 下面实现它也不起作用,因为 expected.I 失败了明白我哪里错了。
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();
}
试试这个
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();
}
}
}
}