Java Force Delete forceDelete(File file)

Here you can find the source of forceDelete(File file)

Description

A "brute force" method to delete a file that might be in use by another thread or application.

License

Open Source License

Parameter

Parameter Description
file the file to be deleted

Return

true if the delete operation succeded, and false otherwise.

Declaration

public static boolean forceDelete(File file) 

Method Source Code

//package com.java2s;
/*/*  w  w  w.  j a  v  a2  s.  c om*/
 * Copyright 2004-2009 Luciano Vernaschi
 *
 * This file is part of MeshCMS.
 *
 * MeshCMS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * MeshCMS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with MeshCMS.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.File;

public class Main {
    /**
     * A "brute force" method to delete a file that might be in use by
     * another thread or application. This method simply tries again and again
     * for 20 seconds then gives up.
     *
     * @param file the file to be deleted
     *
     * @return <code>true</code> if the delete operation succeded, and <code>false<code> otherwise.
     */
    public static boolean forceDelete(File file) {
        if (!file.exists()) {
            return true;
        }

        /* do not force on directories */
        if (file.isDirectory()) {
            return file.delete();
        }

        for (int i = 1; i < 20; i++) {
            if (file.delete()) {
                return true;
            }

            try {
                Thread.sleep(i * 100L);
            } catch (InterruptedException ex) {
            }
        }

        return false;
    }
}

Related

  1. forceDelete(File f)
  2. forceDelete(File f)
  3. forceDelete(File file)
  4. forceDelete(File file)
  5. forceDelete(File file)
  6. forceDelete(File file)
  7. forceDelete(File file)