michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this file, michael@0: * You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: package org.mozilla.gecko.util; michael@0: michael@0: import android.util.Log; michael@0: michael@0: import java.io.File; michael@0: import java.io.IOException; michael@0: import java.io.FilenameFilter; michael@0: michael@0: import org.mozilla.gecko.mozglue.RobocopTarget; michael@0: michael@0: public class FileUtils { michael@0: private static final String LOGTAG= "GeckoFileUtils"; michael@0: /* michael@0: * A basic Filter for checking a filename and age. michael@0: **/ michael@0: static public class NameAndAgeFilter implements FilenameFilter { michael@0: final private String mName; michael@0: final private double mMaxAge; michael@0: michael@0: public NameAndAgeFilter(String name, double age) { michael@0: mName = name; michael@0: mMaxAge = age; michael@0: } michael@0: michael@0: @Override michael@0: public boolean accept(File dir, String filename) { michael@0: if (mName == null || mName.matches(filename)) { michael@0: File f = new File(dir, filename); michael@0: michael@0: if (mMaxAge < 0 || System.currentTimeMillis() - f.lastModified() > mMaxAge) { michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: } michael@0: michael@0: @RobocopTarget michael@0: public static void delTree(File dir, FilenameFilter filter, boolean recurse) { michael@0: String[] files = null; michael@0: michael@0: if (filter != null) { michael@0: files = dir.list(filter); michael@0: } else { michael@0: files = dir.list(); michael@0: } michael@0: michael@0: if (files == null) { michael@0: return; michael@0: } michael@0: michael@0: for (String file : files) { michael@0: File f = new File(dir, file); michael@0: delete(f, recurse); michael@0: } michael@0: } michael@0: michael@0: public static boolean delete(File file) throws IOException { michael@0: return delete(file, true); michael@0: } michael@0: michael@0: public static boolean delete(File file, boolean recurse) { michael@0: if (file.isDirectory() && recurse) { michael@0: // If the quick delete failed and this is a dir, recursively delete the contents of the dir michael@0: String files[] = file.list(); michael@0: for (String temp : files) { michael@0: File fileDelete = new File(file, temp); michael@0: try { michael@0: delete(fileDelete); michael@0: } catch(IOException ex) { michael@0: Log.i(LOGTAG, "Error deleting " + fileDelete.getPath(), ex); michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Even if this is a dir, it should now be empty and delete should work michael@0: return file.delete(); michael@0: } michael@0: }