File类

1.创建文件

//创建文件夹
        File file1 = new File("d:\\test");
        file1.mkdir();
        //创建文本
        File file2 = new File("d:\\test\\data.txt");
        try {
            file2.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建多级文件夹
        File file3 = new File("d:\\test\\11\\22");
        file3.mkdirs();

如果文件或文件夹已经存在则不会重新创建.

2.删除文件

//删除文本
        File file1 = new File("d:\\test\\data.txt");
        if(file1.exists()) {
            file1.delete();
            System.out.println("删除" + file1 + "成功");
        }
        //删除文件夹
        File file2 = new File("d:\\test\\11\\22");
        if(file2.exists()) {
            file2.delete();
            System.out.println("删除" + file2 + "成功");
        }

3.获取文件信息

        //获取文件名字
        file2.getName();
        //获取文件路径
        file2.getPath();

4.实现一个案例

手动输入一个路径 然后遍历出路径下的所有文件
    public class FileDemo {
    public static void main(String[] args) {
        //手动输入一个路径 然后遍历出路径下的所有文件
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            //获取输入的路径
            String path = br.readLine();
            File file = new File(path);
            //exists 如果是文件或者是文件夹就返回true
            if (file.exists()) {
                fileList(file);
            } else {
                System.out.println("文件路径有误");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void fileList(File filePath) {
        File[] list = filePath.listFiles();
        for (File f : list) {
            if (f.isFile()) {
                System.out.println(f.getName());
            } else {
                fileList(f);
            }
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w7486

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值