Java File Delete nio deleteAll(File file)

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

Description

Deletes all files and directory specified recursively including passed file itself.

License

Open Source License

Parameter

Parameter Description
file a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static void deleteAll(File file) throws IOException 

Method Source Code


//package com.java2s;

import java.io.File;

import java.io.IOException;

import java.nio.file.Files;

import java.util.LinkedList;

public class Main {
    /**//from  ww  w .j a va 2  s.com
     * Deletes all files and directory specified recursively including passed
     * file itself.
     * 
     * @param file
     * @throws IOException
     */
    public static void deleteAll(File file) throws IOException {
        if (file == null || !file.exists()) {
            return;
        }

        if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                deleteAll(f);
            }
        }

        /**
         * <p>
         * If file is read-only delete may fail. This might happen for example
         * for git's object, pack and idx files. Therefore it's needed to
         * firstly set them writeable.
         */
        if (!file.isDirectory()) {
            if (!file.setWritable(true, false)) {
                throw new IOException(String.format("Failed to change file to writeable [%s].", file));
            }
        }
        Files.delete(file.toPath());
    }

    /**
     * Lists all files starting with prefix specified located in the directory.
     * 
     * @param directory
     *            The directory to search in.
     * @param prefix
     *            Prefix of files to be listed.
     * @param suffix
     *            Suffix of files to be listed.
     * @return
     */
    public static File[] listFiles(File directory, String prefix, String suffix) {
        final String f_prefix = prefix != null ? prefix : "";
        final String f_suffix = suffix != null ? suffix : "";

        LinkedList<File> files = new LinkedList<>();
        for (File f : directory.listFiles()) {
            if (f.getName().startsWith(f_prefix) && f.getName().endsWith(f_suffix)) {
                files.add(f);
            }
        }

        return files.toArray(new File[files.size()]);
    }
}

Related

  1. delete(File file)
  2. delete(File file)
  3. delete(File toRecurse)
  4. delete(final File directory, final FileFilter fileFilter)
  5. deleteAll(File f)
  6. deleteEntriesFromZip(File zipFile, List entriesToDelete)
  7. deleteFile(File f)
  8. deleteFile(File f)
  9. deleteFile(String fileName)