java 文件不存在自动创建文件 java 文件是否存在

目录

1、判断文件是否存在

2、判断文件夹是否存在

2.1、file.mkdirs()创建出的文件夹

2.2、 file.getParentFile().mkdirs();


1、判断文件是否存在

import java.io.File;

public class dome {
    public static void main(String[] args) throws Exception {
        File file = new File("E:\upload\protocol");
        if(file.exists()){
            System.out.println("文件存在");
            file.delete();//删除文件
        }else{
            System.out.println("文件不存在");
            file.createNewFile();//创建失败会抛出异常throw new IOException("Invalid file path");
        }
    }
}

2、判断文件夹是否存在

public class dome {
    public static void main(String[] args) throws Exception {
        File file = new File("E:\upload\protocol");
        if(!file.exists()&& !file.isDirectory()){
            System.out.println("文件夹不存在");
            file.mkdirs();                        //把a.sql也当做文件夹名来创建
            file.getParentFile().mkdirs();       //获取路径的根路径领创建文件,到最后最后一级路径前E:\新建文件夹\20211110\
        }else{
            System.out.println("文件夹存在");
        }
    }
}

2.1、file.mkdirs()创建出的文件夹

 2.2、 file.getParentFile().mkdirs();

猜你喜欢

转载自blog.csdn.net/weixin_52208686/article/details/131896852