JavaSE_io_根据路径逐层创建文件夹 (代码实现)

本文介绍了一个Java实用工具类,用于递归地创建文件路径中不存在的目录。该工具类支持Windows和Linux操作系统,并提供了具体实现代码。


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.youkuaiyun.com/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();
        }
    }
}


参考文章


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值