集册 Java实例教程 删除文件,从不引发异常。

删除文件,从不引发异常。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

523
删除文件,永不引发异常。

/*

 * Licensed to the Apache Software Foundation (ASF) under one or more

 * contributor license agreements.  See the NOTICE file distributed with

 * this work for additional information regarding copyright ownership.

 * The ASF licenses this file to You under the Apache License, Version 2.0

 * (the "License"); you may not use this file except in compliance with

 * the License.  You may obtain a copy of the License at

 * 

 *      http://www.apache.org/licenses/LICENSE-2.0

 * 

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

//package com.nowjava;
/**来 自 n o w j a v a . c o m - 时代Java**/

import java.io.File;


import java.io.FileNotFoundException;


import java.io.IOException;


public class Main {

    public static void main(String[] argv) throws Exception {

        File file = new File("Main.java");

        System.out.println(deleteQuietly(file));/** 来 自 N o w  J a v a  .   c o m**/

    }


    /**

     * Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.

     * <p>

     * The difference between File.delete() and this method are:

     * <ul>

     * <li>A directory to be deleted does not have to be empty.</li>

     * <li>No exceptions are thrown when a file or directory cannot be deleted.</li>

     * </ul>

     *

     * @param file  file or directory to delete, can be <code>null</code>

     * @return <code>true</code> if the file or directory was deleted, otherwise

     * <code>false</code>

     *

     * @since Commons IO 1.4

     */

    public static boolean deleteQuietly(File file) {

        if (file == null) {

            return false;

        }

        try {

            if (file.isDirectory()) {

                cleanDirectory(file);

            }

        } catch (Exception ignored) {

        }


        try {

            return file.delete();

        } catch (Exception ignored) {

            return false;

        }

    }


    /**

     * Cleans a directory without deleting it.

     *

     * @param directory directory to clean

     * @throws IOException in case cleaning is unsuccessful

     */

    private static void cleanDirectory(File directory) throws IOException {

        if (!directory.exists()) {

            String message = directory + " does not exist";

            throw new IllegalArgumentException(message);

        }


        if (!directory.isDirectory()) {

            String message = directory + " is not a directory";

            throw new IllegalArgumentException(message);

        }


        File[] files = directory.listFiles();

        if (files == null) { // null if security restricted

            throw new IOException("Failed to list contents of " + directory);

        }


        IOException exception = null;

        for (File file : files) {

            try {

                forceDelete(file);

            } catch (IOException ioe) {

                exception = ioe;

            }

        }


        if (null != exception) {

            throw exception;

        }

    }


    /**

     * Deletes a file. If file is a directory, delete it and all sub-directories.

     * <p>

     * The difference between File.delete() and this method are:

     * <ul>

     * <li>A directory to be deleted does not have to be empty.</li>

     * <li>You get exceptions when a file or directory cannot be deleted.

     *      (java.io.File methods returns a boolean)</li>

     * </ul>

     *

     * @param file  file or directory to delete, must not be <code>null</code>

     * @throws NullPointerException if the directory is <code>null</code>

     * @throws FileNotFoundException if the file was not found

     * @throws IOException in case deletion is unsuccessful

     */

    public static void forceDelete(File file) throws IOException {

        if (file.isDirectory()) {

            deleteDirectory(file);

        } else {

            boolean filePresent = file.exists();

            if (!file.delete()) {

                if (!filePresent) {

                    throw new FileNotFoundException("File does not exist: "

                            + fil
展开阅读全文