Java Create Directory mkdirs(File path)

Here you can find the source of mkdirs(File path)

Description

File.mkdirs() method doesn't work when multiple threads are creating paths with a common parent directory simultaneously.

License

Open Source License

Declaration

public static boolean mkdirs(File path) 

Method Source Code

//package com.java2s;
/*/*  w w  w  .j  a va2 s. c om*/
 * ***** BEGIN LICENSE BLOCK *****
 * Zimbra Collaboration Suite Server
 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012, 2013, 2014, 2015, 2016 Synacor, Inc.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software Foundation,
 * version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with this program.
 * If not, see <https://www.gnu.org/licenses/>.
 * ***** END LICENSE BLOCK *****
 */

import java.io.File;

import java.io.IOException;

public class Main {
    /**
     * File.mkdirs() method doesn't work when multiple threads are
     * creating paths with a common parent directory simultaneously.
     * Use this method instead.
     * @return
     */
    public static boolean mkdirs(File path) {
        if (path.exists()) {
            return true;
        }
        // mkdir() may return false if another thread creates the directory
        // after the above exists() check but before the mkdir() call.
        // As far as this thread is concerned it's a successful mkdirs().
        if (path.mkdir() || path.exists()) {
            return true;
        }
        File canonFile = null;
        try {
            canonFile = path.getCanonicalFile();
        } catch (IOException e) {
            return false;
        }
        String parent = canonFile.getParent();
        if (parent != null) {
            File pf = new File(parent);
            return mkdirs(pf) && (canonFile.mkdir() || canonFile.exists());
        } else
            return false;
    }
}

Related

  1. mkDirRec(File file)
  2. mkdirs(File folder)
  3. mkdirs(File outdir, String path)
  4. mkdirs(File parent, String name, boolean mkdirs)
  5. mkdirs(File path)
  6. mkDirs(File path)
  7. mkdirs(File path)
  8. mkdirs(final File aDirectory)
  9. mkdirs(final File dirs)