File 的mkdirs 建立資料夾
阿新 • • 發佈:2019-02-09
//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