【问题标题】:Delete files older than given time from directory从目录中删除早于给定时间的文件
【发布时间】:2014-09-12 11:33:31
【问题描述】:

在我的应用程序中打开一次后,我创建了文件列表以存储某些属性。 每次打开文件时,这些属性都会更改,因此我将它们删除并重新创建。

我已经使用

创建了所有文件文件
File file =new File(getExternalFilesDir(null),
                currentFileId+"");
if(file.exists()){
           //I store the required attributes here and delete them
           file.delete();
}else{
          file.createNewFile();
}

我想删除一周前的所有这些文件,因为不再需要这些存储的属性。 这样做的合适方法是什么?

【问题讨论】:

  • 如果您的属性是数字或字符串,那么创建文件来临时存储属性听起来是个坏主意。将数据存储在 SQL 数据库中可能会更加高效和实用。
  • 那些文件非常小 我想知道如果那些文件数量过多并填满内存空间相对较小的设备的内存,就会产生问题。仅出于此目的,我想删除这些文件。

标签: android file-io


【解决方案1】:

这应该可以解决问题。它将创建一个到 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();
    }

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

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;
}

【讨论】:

  • 文件文件 =new File(getExternalFilesDir(null), currentFileId+"");它创建以 id 命名的文件。我想在不知道文件名的情况下删除文件,因为我不会记住每个文件的所有这些 id
  • 然后你可以迭代目录中的所有文件,并检查它们是否超过 7 天。
  • 我在迭代中遇到问题,不知道我想删除它们的文件名
  • 您不必知道文件的名称,因为它们存储在文件数组中...为什么要名称?
  • 谢谢我的解决方案结合@Sagar Pilkhwal
【解决方案2】:
if (file.exists()) {
  Date today = new Date();

  int diffInDays = (int)( (today.getTime() - file.lastModified()) /(1000 * 60 * 60 * 24) );
  if(diffInDays>7){
            System.out.println("File is one week old");
            //you can delete the file here
    }
}

【讨论】:

  • 无需将文件的修改长转换为日期,因为无论如何您都在使用毫秒。但总的来说也是一个不错的方法。
  • 感谢我的解决方案 :) 将您的代码与 @PedroOliveira 结合起来
  • 一周还是一天? :P
  • if(diffInDays&gt;7) 一周前,很高兴你找到了答案,如果可能的话,请投票
【解决方案3】:

File.lastModified() 在Unix Time 中返回一个long Int

【讨论】:

    猜你喜欢
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 2012-04-02
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多