File 的mkdirs 创建文件夹

//File中mkdirs的实现
  public boolean mkdirs() {
        if (exists()) {
            return false;
        }
        if (mkdir()) {//【1】
            return true;
        }
        File canonFile = null;
        try {//【2】
            canonFile = getCanonicalFile();
        } catch (IOException e) {
            return false;
        }

        File parent = canonFile.getParentFile();
        return (parent != null && (parent.mkdirs() || parent.exists()) &&
                canonFile.mkdir());//【3】
    }
mkdirs()可以建立多级文件夹, mkdir()只会建立一级的文件夹, 如下:
new File("/tmp/one/two/three").mkdirs();
执行后, 会建立tmp/one/two/three四级目录
new File("/tmp/one/two/three").mkdir();
则不会建立任何目录, 因为找不到/tmp/one/two目录, 结果返回false

猜你喜欢

转载自blog.csdn.net/u011586504/article/details/80079567