欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java 删除目录的方法(空和非空),,空目录很好删,非空目录就

来源: javaer 分享于  点击 12835 次 点评:29

Java 删除目录的方法(空和非空),,空目录很好删,非空目录就


空目录很好删,非空目录就需要采用递归的方法去删

import java.io.File;public class DeleteDirectory {    /**     * Deletes the directory passed in.     * @param dir Directory to be deleted     */    private static void doDeleteEmptyDir(String dir) {        boolean success = (new File(dir)).delete();        if (success) {            System.out.println("Successfully deleted empty directory: " + dir);        } else {            System.out.println("Failed to delete empty directory: " + dir);        }    }    /**     * Deletes all files and subdirectories under "dir".     * @param dir Directory to be deleted     * @return boolean Returns "true" if all deletions were successful.     *                 If a deletion fails, the method stops attempting to     *                 delete and returns "false".     */    private static boolean deleteDir(File dir) {        if (dir.isDirectory()) {            String[] children = dir.list();            for (int i=0; i<children.length; i++) {                boolean success = deleteDir(new File(dir, children[i]));                if (!success) {                    return false;                }            }        }        // The directory is now empty so now it can be smoked        return dir.delete();    }    /**     * Sole entry point to the class and application.     * @param args Array of String arguments.     */    public static void main(String[] args) {        doDeleteEmptyDir("new_dir1");        String newDir2 = "new_dir2";        boolean success = deleteDir(new File(newDir2));        if (success) {            System.out.println("Successfully deleted populated directory: " + newDir2);        } else {            System.out.println("Failed to delete populated directory: " + newDir2);        }    }}//该片段来自于http://byrx.net
相关栏目:

用户点评