2014-09-12 63 views
6

我已經創建了一些文件列表,以便在應用程序中打開一次後才能存儲某些屬性。 每次打開文件時,這些屬性都會更改,因此我將它們刪除並重新創建。從目錄中刪除比給定時間早的文件

我一直在使用

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

我想刪除所有在這裏一個多星期年長這些文件的,與存儲的屬性將不再需要任何更多創建的所有文件的文件。 這樣做的適當方法是什麼?

+1

創建文件臨時存儲屬性聽起來像一個壞主意,如果你的屬性是數字或字符串。 將數據存儲在SQL數據庫中可能更加高效和實用。 – Christian 2014-09-12 11:46:36

+0

這些文件的尺寸很小 我不知道這些文件的數量是否會增加,並且使用相對較小的內存空間填充設備的內存,這會產生問題。 僅用於此目的我想刪除這些文件。 – 2014-09-12 11:50:01

回答

14

這應該做的伎倆。它將在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; 
} 
+0

File file = new File(getExternalFilesDir(null), currentFileId +「」); 它創建與id.I的filenamed我想刪除文件,而不知道文件名是什麼,因爲我不會記住每個文件的所有這些id – 2014-09-12 11:45:42

+1

然後,您可以遍歷目錄中的所有文件,並檢查他們是否他們大於7天。 – 2014-09-12 11:49:12

+0

我在迭代時遇到問題,不知道文件名我想刪除它們 – 2014-09-12 11:52:14

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 
    } 
} 
+0

無論如何,無需將文件的修改過的長整型轉換爲日期,因爲您仍然使用毫秒。但總體來說也是一個好方法。 – 2014-09-12 11:56:00

+0

謝謝我得到了我的解決方案:)結合你的代碼與@PedroOliveira – 2014-09-13 10:18:49

+0

是一週還是一天? :P – 2014-09-13 10:28:24