Java File Delete delete(File file)

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

Description

Delete a file or directory.

License

Open Source License

Parameter

Parameter Description
file The file or directory.

Exception

Parameter Description
IOException For IO Errors.

Declaration

public static void delete(File file) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import java.io.IOException;

public class Main {
    private static final File[] EMPTY_FILE_ARRAY = new File[0];

    /**/*from  w w w  . java  2s.c  o m*/
     * Delete a file or directory.
     * 
     * @param file
     *            The file or directory.
     * @throws IOException
     *             For IO Errors.
     */
    public static void delete(File file) throws IOException {
        if (file.isDirectory()) {
            deleteDir(file);
        } else {
            deleteFile(file);
        }
    }

    /**
     * Delete a directory and all of its contents.
     * 
     * @param dir
     *            The directory.
     * @throws IOException
     *             If something cannot be deleted.
     */
    public static void deleteDir(File dir) throws IOException {
        if (!dir.exists()) {
            return;
        }
        File[] files = listFiles(dir);
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isDirectory()) {
                deleteDir(file);
            } else {
                deleteFile(file);
            }
        }
        dir.delete();
    }

    /**
     * Delete file.
     * 
     * @param file
     *            The file.
     * @throws IOException
     *             If the file was not deleted.
     */
    private static void deleteFile(File file) throws IOException {
        boolean success = file.delete();
        if (!success) {
            throw new IOException("Could not delete " + file);
        }
    }

    /**
     * Utility method to list files but return an empty array instead of null for no results.
     * 
     * @param dir
     *            The directory.
     * @return The array of files.
     */
    public static File[] listFiles(File dir) {
        File[] files = dir.listFiles();
        if (files == null) {
            files = EMPTY_FILE_ARRAY;
        }
        return files;
    }
}

Related

  1. delete(File file)
  2. delete(File file)
  3. delete(File file)
  4. delete(File file)
  5. delete(File file)
  6. delete(File file)
  7. delete(File file)
  8. delete(File file)
  9. delete(File file)