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

时间:2023-03-08 20:12:39

功能

这个实例实现了在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 ?");
        }
    }
}

如有不当之处欢迎指出!