Java Delete File or Directory deleteFileOrDirectory(File dir)

Here you can find the source of deleteFileOrDirectory(File dir)

Description

delete a file or directory

License

Open Source License

Parameter

Parameter Description
dir the file or directory to delete

Exception

Parameter Description
IOException an exception

Return

if dir has been deleted

Declaration

public static boolean deleteFileOrDirectory(File dir) throws IOException 

Method Source Code


//package com.java2s;
/*/*from   w  ww  . j  a v a2 s  .  com*/
 * Copyright (C) 2010 Alex Cojocaru
 * 
 * This program 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.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.*;

public class Main {
    /**
     * delete a file or directory
     * @param dir the file or directory to delete
     * @return if dir has been deleted
     * @throws IOException
     */
    public static boolean deleteFileOrDirectory(File dir) throws IOException {
        if (!dir.exists())
            return true;

        // if it is a file, delete and return the result
        if (dir.isFile())
            return dir.delete();

        // recursively delete the directory content, and then the directory itself
        File fis[] = dir.listFiles();
        for (int i = 0; i < fis.length; i++)
            deleteFileOrDirectory(fis[i]);

        return dir.delete();
    }

    /**
     * @param filepath the path of the file whose existence has to be verified
     * @return true if the file denoted by filepath exists
     */
    public static boolean exists(String filepath) {
        return new File(filepath).exists();
    }
}

Related

  1. deleteFileOrDir(File fd)
  2. deleteFileOrDir(File file)
  3. deleteFileOrDir(File file)
  4. deleteFileOrDir(File filehandle)
  5. deleteFileOrDir(File instanceFileOrDir)
  6. deleteFileOrDirectory(File file)
  7. deleteFileOrDirectory(File fileOrDirectory)
  8. deleteFileOrDirectory(String fileName)
  9. deleteFileOrDirectoryRecursive(String dir)