文件操作总结

文件操作工具类:

    /**
     * 判断一个文件夹是否存在,若不存在则创建
     * @param dirPath 文件夹路径 例:"D:\\dir"
     */
    public static void createDocument(String dirPath){
        File file = new File(dirPath);
        //判断文件夹是否存在
        if(!file.exists()){
            //创建文件夹
            boolean b = file.mkdirs();
            //根据创建文件夹成功与否打印日志
            if(b){
                System.out.println("创建文件夹成功!");
            }else{
                System.out.println("创建文件夹失败!");
            }
        }
    }

    /**
     * 判断一个文件是否存在
     * @param filePath 文件的路径 举例:"D:\\test-utf.txt"
     * @return true:表示文件存在  false:表示文件不存在
     */
    public static boolean judgeFile(String filePath){
        boolean b = true;

        File file = new File(filePath);

        //判断文件是否存在
        if(!file.exists()){
            //文件不存在
            b = false;
        }

        return b;
    }

    /**
     * 判断一个文件是否存在,若不存在则创建
     * @param dirPath 文件的存放路径 例:"D:\\dir"
     * @param fileName 文件名
     */
    public static void createFile(String dirPath, String fileName){

        try{
            File dir = new File(dirPath);
            //判断文件夹是否存在,若不存在则创建
            if (!dir.exists()){
                dir.mkdirs();
            }

            File file = new File(dirPath, fileName);
            //判断文件夹是否存在
            if(!file.exists()){
                //创建文件夹
                boolean b = file.createNewFile();
                //根据创建文件夹成功与否打印日志
                if(b){
                    System.out.println("创建文件成功!");
                }else{
                    System.out.println("创建文件失败!");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

main方法:

    public static void main(String[] args) {

        System.out.println("**************对文件夹进行判断和创建******************");
        //第一步:判断文件夹是否存在
        String dir1 = "D:\\TestDir1";
        System.out.println("文件夹"+ dir1 +"是否存在:" + judgeFile(dir1));
        //第二步: 创建文件夹
        createDocument(dir1);
        System.out.println("文件夹"+ dir1 +"是否存在:" + judgeFile(dir1));

        System.out.println("**************对文件进行判断和创建******************");
        //第一步:判断文件是否存在
        String dir2 = "D:\\TestDir2";
        String fileName = "test2.txt";
        String filePath = dir2 + "\\" + fileName;
        System.out.println("文件"+ filePath +"是否存在:" + judgeFile(filePath));
        //第二步: 创建文件
        createFile(dir2, fileName);
        System.out.println("文件"+ filePath +"是否存在:" + judgeFile(filePath));
    }

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值