IO流-创建删除文件以及一般API

本文介绍了使用Java IO流的三种方法创建文件,并展示了如何获取文件信息以及删除文件和包含文件的文件夹。内容包括:创建新文件、获取文件属性(如名称、路径、大小等)、基础文件删除以及递归删除含文件的文件夹。通过实例代码详细解析了每个操作的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


使用IO流创建文件,三种方式

package IO流.CreateFile;

import java.io.File;
import java.io.IOException;

/**
 * @program:多线程和IO
 * @descripton:创建新文件
 * @author:ZhengCheng
 * @create:2021/10/4-13:24
 **/
public class CreateNewFile {
    public static void main(String[] args) {
        CreateNewFile cnf = new CreateNewFile();
        cnf.createNewFile01("e:\\new1.txt");
        cnf.createNewFile02("e:\\","new2.txt");
        cnf.createNewFile03("e:\\","new3.txt");
    }
    //路径与文件名
    public void createNewFile01(String filepath){
        File file = new File(filepath);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //父路径+子名
    public void createNewFile02(String father,String child){
        File file = new File(father,child);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //父文件加子名字
    public void createNewFile03(String father,String child){
        File Ffile = new File(father);
        File file = new File(Ffile,child);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

 一些基本的File的API

public void fileInfo(){
    File file = new File("e:\\new1.txt");
    System.out.println("文件名字=" + file.getName());
    System.out.println("文件绝对路径=" + file.getAbsolutePath());
    System.out.println("文件父级目录=" + file.getParent());
    System.out.println("文件大小(字节)=" + file.length());
    System.out.println("文件是否存在=" + file.exists());
    System.out.println("是不是一个文件=" + file.isFile());
    System.out.println("是不是一个目录=" + file.isDirectory());
}

 删除文件,一般的文件,和空文件夹,我们都可以直接使用delete删除。但是如果文件夹中存在东西,那么,我们需要使用别的方法。

基础删除方法:

File file = new File("e:\\new1.txt");
if (file.exists()){
    file.delete();
}

 删除内含文件的文件夹(包括该文件夹)

public void dirsDelete(String path) {
    File file = new File(path);
    String[] fileContent = file.list();
    for (String conPath : fileContent) {
        File file1 = new File(file, conPath);
        //递归向下删除
        if (file1.isDirectory()) {
            dirsDelete(file1.getAbsolutePath());
            file1.delete();//空了,删除
        } else {
            file1.delete();
        }
    }
    file.delete();//删除最顶层父目录,没有这句话可以当做清空path文件夹。
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值