1. 程式人生 > >JavaSE_io_根據路徑逐層建立資料夾 (程式碼實現)

JavaSE_io_根據路徑逐層建立資料夾 (程式碼實現)

Java 中,建立 file 時,必須要 路徑上的目錄存在時,才能建立檔案,否則會丟擲異常。

所以需要對檔案路徑上的目錄一一建立,下面給出這樣一個實現。 

import java.io.File;

/**
 * Created by szh on 2017/10/12.
 */
public class DirectoryUtil {

    private static String WIN_SEPARATOR = new String("\\");
    private static String LINUX_SEPARATOR = new String("/");

    public void createParentDir(String path) throws Exception {
        String systemSeparator = File.separator;
        if (systemSeparator.equals(WIN_SEPARATOR)) {
            createParentDirWIN(path);
        } else if (systemSeparator.equals(LINUX_SEPARATOR)) {
            createParentDirLinux(path);
        }
    }

    //Windows
    public void createParentDirWIN(String path) throws Exception {

        //Split中特殊字元分割: http://blog.csdn.net/myfmyfmyfmyf/article/details/37592711
        // \ 用 “\\\\”
        String[] pathArr = path.split("\\\\");
        System.out.println("length : " + pathArr.length);

        StringBuffer tmpPath = new StringBuffer();
        for (int i = 0; i < pathArr.length; i++) {
            tmpPath.append(pathArr[i]).append(WIN_SEPARATOR);

            if (0 == i) continue;

            File file = new File(tmpPath.toString());

            if (!file.exists()) {
                file.mkdir();
                System.out.println("當前建立的目錄是 : " + tmpPath.toString());
            }

        }
    }

    //Linux
    public void createParentDirLinux(String path) throws Exception {

        String[] pathArr = path.split(LINUX_SEPARATOR);

        StringBuffer tmpPath = new StringBuffer();
        for (int i = 0; i < pathArr.length; i++) {
            tmpPath.append(pathArr[i]).append(LINUX_SEPARATOR);

            File file = new File(tmpPath.toString());
            if (!file.exists()) {
                file.mkdir();
                System.out.println("當前建立的目錄是 : " + tmpPath.toString());
            }
        }
    }

    public static void main(String[] args){
        DirectoryUtil directoryUtil = new DirectoryUtil();
        try{
            directoryUtil.createParentDir("E:\\testCreate\\dmp\\FirstPartyAudience\\2017\\ss\\");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}


參考文章