mobile/android/base/util/FileUtils.java

changeset 0
6474c204b198
equal deleted inserted replaced
-1:000000000000 0:ebfc64791489
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 package org.mozilla.gecko.util;
6
7 import android.util.Log;
8
9 import java.io.File;
10 import java.io.IOException;
11 import java.io.FilenameFilter;
12
13 import org.mozilla.gecko.mozglue.RobocopTarget;
14
15 public class FileUtils {
16 private static final String LOGTAG= "GeckoFileUtils";
17 /*
18 * A basic Filter for checking a filename and age.
19 **/
20 static public class NameAndAgeFilter implements FilenameFilter {
21 final private String mName;
22 final private double mMaxAge;
23
24 public NameAndAgeFilter(String name, double age) {
25 mName = name;
26 mMaxAge = age;
27 }
28
29 @Override
30 public boolean accept(File dir, String filename) {
31 if (mName == null || mName.matches(filename)) {
32 File f = new File(dir, filename);
33
34 if (mMaxAge < 0 || System.currentTimeMillis() - f.lastModified() > mMaxAge) {
35 return true;
36 }
37 }
38
39 return false;
40 }
41 }
42
43 @RobocopTarget
44 public static void delTree(File dir, FilenameFilter filter, boolean recurse) {
45 String[] files = null;
46
47 if (filter != null) {
48 files = dir.list(filter);
49 } else {
50 files = dir.list();
51 }
52
53 if (files == null) {
54 return;
55 }
56
57 for (String file : files) {
58 File f = new File(dir, file);
59 delete(f, recurse);
60 }
61 }
62
63 public static boolean delete(File file) throws IOException {
64 return delete(file, true);
65 }
66
67 public static boolean delete(File file, boolean recurse) {
68 if (file.isDirectory() && recurse) {
69 // If the quick delete failed and this is a dir, recursively delete the contents of the dir
70 String files[] = file.list();
71 for (String temp : files) {
72 File fileDelete = new File(file, temp);
73 try {
74 delete(fileDelete);
75 } catch(IOException ex) {
76 Log.i(LOGTAG, "Error deleting " + fileDelete.getPath(), ex);
77 }
78 }
79 }
80
81 // Even if this is a dir, it should now be empty and delete should work
82 return file.delete();
83 }
84 }

mercurial