从目录中删除超过给定时间的文件

A_r*_*mas 7 file-io android

我已经创建了一些文件列表,用于在我的应用程序中打开一个属性后存储它们.每次打开文件时,这些属性都会更改,因此我将其删除并再次创建.

我已经使用创建了所有文件文件

File file =new File(getExternalFilesDir(null),
                currentFileId+"");
if(file.exists()){
           //I store the required attributes here and delete them
           file.delete();
}else{
          file.createNewFile();
}
Run Code Online (Sandbox Code Playgroud)

我想在这里删除超过一周的所有这些文件,因为不再需要那些存储的属性.这样做的适当方法是什么?

Ped*_*ira 18

这应该可以解决问题.它将在7天前创建一个日历实例,并比较文件的修改日期是否在该时间之前.如果是这意味着该文件超过7天.

    if(file.exists()){
        Calendar time = Calendar.getInstance();
        time.add(Calendar.DAY_OF_YEAR,-7);
        //I store the required attributes here and delete them
        Date lastModified = new Date(file.lastModified());
        if(lastModified.before(time.getTime())) {
            //file is older than a week
            file.delete();
        }
    }else{
        file.createNewFile();
    }
Run Code Online (Sandbox Code Playgroud)

如果要获取目录中的所有文件,可以使用它,然后迭代结果并比较每个文件.

public static ArrayList<File> getAllFilesInDir(File dir) {
    if (dir == null)
        return null;

    ArrayList<File> files = new ArrayList<File>();

    Stack<File> dirlist = new Stack<File>();
    dirlist.clear();
    dirlist.push(dir);

    while (!dirlist.isEmpty()) {
        File dirCurrent = dirlist.pop();

        File[] fileList = dirCurrent.listFiles();
        for (File aFileList : fileList) {
            if (aFileList.isDirectory())
                dirlist.push(aFileList);
            else
                files.add(aFileList);
        }
    }

    return files;
}
Run Code Online (Sandbox Code Playgroud)