[英]Deleting all but the last 3 modified files in a directory
I have a directory of backups saved on the phone, but I can't work out the logic to remove all but the last three.我在手机上保存了一个备份目录,但我无法找出删除除最后三个之外的所有备份的逻辑。
As it stands I have:就目前而言,我有:
public static void checkLocalBackup(){
String path = Global.backupSingleLocalLocation;
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
for (int i=0; i < file.length; i++)
{
Log.d("Files", "FileName:" + file[i].lastModified());
//sudo code
if(isNotInLastThreeFiles){
deleteFile(file[i]);
}
}
}
This loops through and lists all the last modified files, but I cant work out how to select the oldest files and leave the newest 3?这会循环并列出所有最后修改的文件,但我不知道如何选择最旧的文件并保留最新的 3 个文件?
Any guidance will be really appreciated.任何指导将不胜感激。
Store all of the File
objects in a List<File>
and sort them using a custom Comparator
so that they are ordered by "lastModified".将所有File
对象存储在List<File>
,并使用自定义Comparator
对它们进行排序,以便它们按“lastModified”排序。
Finally, select the last three items from the list (or the first three, depending upon your sort order).最后,从列表中选择最后三项(或前三项,取决于您的排序顺序)。
You can sort your files array by modified date:您可以按修改日期对文件数组进行排序:
File[] files = folder.listFiles();
Arrays.sort(files, new Comparator<File>(){
public int compare(File f1, File f2) {
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}
});
This post shows how to list files by modified date;这篇文章展示了如何按修改日期列出文件; once you do that, you can easily find the last three:一旦你这样做了,你可以很容易地找到最后三个:
Best way to list files in Java, sorted by Date Modified? 在 Java 中列出文件的最佳方法,按修改日期排序?
使用 Comparator,您可以轻松实现在所需目录中获取最后三个修改文件的要求。
// delete all except 10 latest files
deleteAllExcept(10);
private static void deleteAllExcept(int i) {
ArrayList<File> files = new ArrayList<>();
for(File file : new File(path_to_folder).listFiles()) {
files.add(file);
System.out.println(file.getName());
}
files.stream()
.filter((File p) -> p.getName().contains("."))
.sorted(getReverseLastModifiedComparator())
.skip(i)
.forEach(x -> ((File) x).delete());
}
private static Comparator<File> getReverseLastModifiedComparator() {
return (File o1, File o2) -> {
if (o1.lastModified() < o2.lastModified()) {
return 1;
}
if (o1.lastModified() > o2.lastModified()) {
return -1;
}
return 0;
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.