2 qq 33179811 qq_33179811 于 2016.03.17 16:45 提问

java递归删除目录的一个小问题

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DeleteFilesDemo {

public static void main(String[] args) throws FileNotFoundException {
    // TODO Auto-generated method stub
    File dir = new File("C:\\CODE\\a");
    deleteDir(dir);
    printTime();
}

public static void deleteDir(File dir) {
    File[] files = dir.listFiles();
    for (File f : files) {
        if (f.isDirectory())
            deleteDir(f);
        else
            System.out.println(f.toString() + "——" + f.delete());
    }
    System.out.println(dir.toString() + "................" + dir.delete());
}

public static void printTime() throws FileNotFoundException {
    String time = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date());
    new PrintStream("c:/code/deleteTime.log").print(time + "\r\n所有目录与文件删除成功!");
}

}

请问,如果递归到一个空目录,再调用一次deleteDir得到的File数组不就是空的了吗?那么遍历的时候为什么不会出现异常呢?

5个回答

gaoshouzhizui
gaoshouzhizui   2016.03.17 17:11
已采纳

这里假设是空目录A,判断是目录,递归调用deleteDir(File dir),然后到了 File[] files = dir.listFiles();这句,由于是空目录所以files=null;所以不进for循环的,就直接删除了。

gaoshouzhizui
gaoshouzhizui listFiles :public File[] listFiles()返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。 如果此抽象路径名不表示一个目录,那么此方法将返回 null。否则返回一个 File 对象数组。这是API里的原话。
接近 2 年之前 回复
enpterexpress
enpterexpress   2016.03.17 16:53

先删除子目录,再删除此目录,怎么会遍历到空目录

qq_33179811
qq_33179811 假如到了if判断一个文件是不是目录的时候,不是要把这个目录里的文件放在File数组里吗?那如果这个目录是空的呢?File数组就不能遍历了啊
接近 2 年之前 回复
fubo1990
fubo1990   2016.03.17 16:59

不是你想的那样。
File[] files = dir.listFiles();
如果files为空及一个空目录,程序就进不了for循环,所有就调不到deleteDir(f)就不会出现你想的那种情况。所有不会抛异常。

fubo1990
fubo1990 for(int i=0;i<10;i++){}
接近 2 年之前 回复
fubo1990
fubo1990 回复qq_33179811:files 已经是空了进for循环前,就会判断的。
接近 2 年之前 回复
qq_33179811
qq_33179811 可为什么进不了for循环啊?
接近 2 年之前 回复
u013772876
u013772876   2016.03.17 17:10

foreach语句,空集不会迭代。

jpbirdy
jpbirdy   2016.03.17 20:44
 /**
     * Returns an array of abstract pathnames denoting the files in the
     * directory denoted by this abstract pathname.
     *
     * <p> If this abstract pathname does not denote a directory, then this
     * method returns {@code null}.  Otherwise an array of {@code File} objects
     * is returned, one for each file or directory in the directory.  Pathnames
     * denoting the directory itself and the directory's parent directory are
     * not included in the result.  Each resulting abstract pathname is
     * constructed from this abstract pathname using the {@link #File(File,
     * String) File(File,&nbsp;String)} constructor.  Therefore if this
     * pathname is absolute then each resulting pathname is absolute; if this
     * pathname is relative then each resulting pathname will be relative to
     * the same directory.
     *
     * <p> There is no guarantee that the name strings in the resulting array
     * will appear in any specific order; they are not, in particular,
     * guaranteed to appear in alphabetical order.
     *
     * <p> Note that the {@link java.nio.file.Files} class defines the {@link
     * java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method
     * to open a directory and iterate over the names of the files in the
     * directory. This may use less resources when working with very large
     * directories.
     *
     * @return  An array of abstract pathnames denoting the files and
     *          directories in the directory denoted by this abstract pathname.
     *          The array will be empty if the directory is empty.  Returns
     *          {@code null} if this abstract pathname does not denote a
     *          directory, or if an I/O error occurs.
     *
     * @throws  SecurityException
     *          If a security manager exists and its {@link
     *          SecurityManager#checkRead(String)} method denies read access to
     *          the directory
     *
     * @since  1.2
     */
    public File[] listFiles() {
        String[] ss = list();
        if (ss == null) return null;
        int n = ss.length;
        File[] fs = new File[n];
        for (int i = 0; i < n; i++) {
            fs[i] = new File(ss[i], this);
        }
        return fs;
    }

return里写了,The array will be empty if the directory is empty.

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!