Java File Delete nio delete(File file)

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

Description

delete

License

Open Source License

Declaration

public static void delete(File file) 

Method Source Code


//package com.java2s;
/*//from   w w  w  . ja  va2 s  .  c  o m
 *  Copyright (c) 2011-2015 The original author or authors
 *  ------------------------------------------------------
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  and Apache License v2.0 which accompanies this distribution.
 *
 *       The Eclipse Public License is available at
 *       http://www.eclipse.org/legal/epl-v10.html
 *
 *       The Apache License v2.0 is available at
 *       http://www.opensource.org/licenses/apache2.0.php
 *
 *  You may elect to redistribute this code under either of these licenses.
 */

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class Main {
    public static void delete(File file) {
        if (file.isFile()) {
            deleteQuietly(file);
        } else if (file.isDirectory()) {
            Path directory = file.toPath();
            try {
                Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.delete(file);
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        Files.delete(dir);
                        return FileVisitResult.CONTINUE;
                    }
                });
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    public static void deleteQuietly(File file) {
        try {
            Files.deleteIfExists(file.toPath());
        } catch (Exception e) {
            // Ignore it.
        }
    }
}

Related

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