Java IO流之创建\删除文件

文件的创建

方式一:根据路径创建一个File对象

// 方式一: new File(String pathName)
    public  static void creat01(){
        String filePath = "d:/doc01.txt";
        File file = new File(filePath);

        try {
            file.createNewFile();
            System.out.println("文件创建成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

方式二:根据父目录文件+子路径创建

// 方式二:new File(File parent, String child)
    // 根据父目录文件+子路径构建
    public static void creat02() {
        File parentFile = new File("d:/"); // 父目录文件
        String fileName = "doc02.txt"; //子路径
        File file = new File(parentFile, fileName);

        try {
            file.createNewFile();
            System.out.println("文件创建成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

方式三:根据父目录+子路径创建

// 方式三 new File(String parent, String child)
    public static void creat03(){
        String parentPath = "d:\\";
        String fileName = "doc03.txt";
        File file = new File(parentPath, fileName);

        try {
            file.createNewFile();
            System.out.println("文件创建成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

文件的删除

使用delete删除一个文件或空目录

//判断文件是否存在,如果存在就删除
    public static void deleteFile() {

        String filePath = "d:/doc01.txt";
        File file = new File(filePath);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println(filePath + ":删除成功!");
            } else {
                System.out.println(filePath + "删除失败!");
            }
        } else {
            System.out.println("该文件不存在!");
        }
    }
//判断目录是否存在,如果存在就删除
    public static void deleteFileOfCatalog() {

        String filePath = "d:/Catalog";
        File file = new File(filePath);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println(filePath + ":删除成功!");
            } else {
                System.out.println(filePath + "删除失败!");
            }
        } else {
            System.out.println("该目录不存在!");
        }
    }

创建目录

	// 判断一个 多级/一级 目录是否存在,不存在则创建
    // 一级目录使用mkdir(), 多级目录使用mkdirs()
    public static void createDir() {
        String dir = "d:/hello/word/demo01";
        File file = new File(dir);
        if (file.exists()) {
            System.out.println(dir + ":存在!");
        } else {
            if (file.mkdirs()) {
                System.out.println(dir + ":创建成功!");
            } else {
                System.out.println(dir + "创建失败!");
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值