在window或者Linux环境下创建文件的Util

本文介绍了如何在Windows和Linux环境中编写一个实用工具函数,用于创建文件。内容涵盖不同操作系统下的文件路径处理和权限设置,确保在不同系统上都能正确创建文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package cn.net.cobot.cobot_biddata_servicemodel;

import java.io.File;


public class DirectoryUtil {

    public static String WIN_SEPARATOR = new String("\\");
    public 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\\aa\\");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值