Java文件及文件夹的创建与删除

功能

    这个实例实现了在D盘创建一个文件和文件夹,并删除它们。

函数介绍

    createNewFile():当文件不存在时,根据绝对路径创建该文件。
    delete():删除文件或者文件夹。
    exists():判断文件或者文件夹是否存在。
    isDirectory():判断是否为文件夹。
    mkdir():创建文件夹。
    mkdirs():创建文件夹及其不存在的任何必须的父目录。(P:好恶心的翻译,原谅英语渣...)


实例代码

package cn.edu.pzhu;

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException {
        //创建文件
        File file = new File("d:\\test_file.txt");
        Test.judgeFileExists(file);

        //创建文件夹
        File dir = new File("d:\\hello\\test_dir");
        Test.judgeDieExists(dir);

        //删除文件和文件夹
        Test.deleteFile(file);
        Test.deleteFile(dir);
    }

    //判断文件是否存在
    public static void judgeFileExists(File file) {
        if (file.exists()) {
            System.out.println("The file exists");
        } else {
            System.out.println("File not exists, create it...");
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //判断文件夹是否存在
    public static void judgeDieExists(File dir) {
        if (dir.exists()) {
            if (dir.isDirectory()) {
                System.out.println("The dir exits.");
            } else {
                System.out.println("The same name file exists, can't create the file.");
            }
        } else {
            System.out.println("The dir doesn't exists, create it.");
            dir.mkdirs();
        }

    }

    //删除文件或者文件夹
    public static void deleteFile(File file) {
        if (file.exists()) {
            //文件存在
            System.out.println(file.getAbsolutePath()+" exists.");
            file.delete();
            System.out.println("File is deleted.");
        } else {
            //文件压根不存在
            System.out.println("File doesn't exists, are you kidding me ?");
        }
    }
}

如有不当之处欢迎指出!

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值