创建文件和文件夹

public class CreatFileUtil
{
 
    //创建文件
    public static boolean createFile(String fileName)
    {
        File file=new File(fileName);
        if(file.exists())
        {
            System.out.println("文件已存在"+fileName+"创建失败");
            return false;
        }
        if(fileName.endsWith(File.separator))  //File.separator=""
        {
            System.out.println("文件不能为目录");
            return false;
        }
        if(!file.getParentFile().exists())
        {
            System.out.println("问价所在的目录不存在,准备创建它");
            if(!file.getParentFile().mkdirs())
            {
                System.out.println("创建文件所在的目录失败!");
                return false;
            }
        }
        try
        {
            if(file.createNewFile())
            {
                System.out.println("创建文件"+file.getAbsolutePath()+"成功");
                return true;
            }
            else 
            {
                System.out.println("创建文件"+file.getAbsolutePath()+"失败");
                return false;
            }
        }
        catch(IOException e)
        {
            System.out.println("创建文件"+file.getAbsolutePath()+"失败");
            e.printStackTrace();
            return false;
        }
 
    }
    //创建目录
    public static boolean creatDir(String dirName)
    {
        File file=new File(dirName);
        if(file.exists())
        {
            System.out.println("创建目录失败"+file.getAbsolutePath()+"目录已经存在");
            return false;
 
        }
 
        if(!dirName.endsWith(File.separator))
            dirName+=File.separator;
        if(file.mkdirs())
        {
 
            System.out.println(file.getAbsolutePath()+"创建成功");
            return true;
        }
        else 
            {
            System.out.println(file.getAbsolutePath()+"创建失败");
            return false; 
            }
 
    }
    public static void main(String []args)
    {
        String string="C:/temp/temp.txt";
        String string2="C:/hhaha";
        createFile(string);
        creatDir(string2);
 
    }
 
 
}
梦里不知身是客,一晌贪欢。
原文地址:https://www.cnblogs.com/dccmmtop/p/5709969.html