File Java/Android

82 篇文章 1 订阅

File

文件,常用的文件相关类。
在这里插入图片描述

创建文件

 创建文件的方法
 1. new File(String pathname) // 根据路径创建一个File对象
 2. new File(File parent,String child) // 根据父目录文件 + 子路径构建
 3. new File(String parent,String child) // 根据父目录 + 子路径构建
 使用上述的方法创建File后,需要调用 createNewFile()方法创建文件
@Test
    public void creatFileTest(){
        String filePath = "D:\\ideaProject\\JJ\\untitled\\src\\file\\2.txt";
        File file = new File(filePath);
        // new File 创建了对象还在内存中,下面的createNewFile语句才在磁盘中创建。
        try {
            boolean newFile = file.createNewFile();
            System.out.println("文件创建成功!!!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void creatFileTest2(){
        String dirPath = "D:\\ideaProject\\JJ\\untitled\\src\\file\\";
        String fileName = "3.txt";
        File file = new File(dirPath,fileName);

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

    @Test
    public void creatFileTest3(){
        File file = new File("D:\\ideaProject\\JJ\\untitled\\src\\file\\");
        String fileName = "4.txt";
        File file1 = new File(file,fileName);

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

创建文件夹

file.mkdirs()是通用的方法,既可以创建一级目录,也可以创建多级目录。

    @Test
    public void dirTest() {
        String filePath = "D:\\ideaProject\\JJ\\untitled\\src\\files";
        File file = new File(filePath);
        // java编程中,目录也是文件,是比较特殊的文件
        // 可以创建一级与多级目录
        file.mkdirs();
        // 仅能创建一级目录
        file.mkdir();
    }

file常用方法

@Test
    private void getFile(){
        // 先创建文件
        File file = new File("D:\\ideaProject\\JJ\\untitled\\src\\file\\1.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.isFile());
        // 判断是否是一个目录
        System.out.println("文件是否为目录 " + file.isDirectory());
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

学知识拯救世界

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

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

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

打赏作者

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

抵扣说明:

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

余额充值