Io流之File的介绍

package Io流;

import org.junit.Test;

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

/**
 * 1.创建文件,文件夹  createNewFile()  mkdir()  mkdirs()
 * 2.删除文件,文件夹  delete()
 * 3.查询文件是否存在  exist()
 * 4.查询文件长度      length()
 * 5.获取文件名
 * 6.获取path();  相似与  AbsolutePath();
 */
public class Demo01 {
    //创建单个文件, 存在不会创建,不存在创建
    @Test
    public void test(){
        try {
            String pathName = "d:\\1.txt";
            File file = new File(pathName);
            boolean newFile = file.createNewFile();
            System.out.println(newFile?"创建成功":"创建失败");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //创建单个文件夹, 存在不会创建,不存在创建
    @Test
    public void test1(){
        String pathName = "d:\\jaba";
        File file = new File(pathName);
        boolean mkdir = file.mkdir();
        System.out.println(mkdir?"创建成功":"创建失败");
    }
    //连续创建多级文件夹,存在不会创建,不存在创建
    @Test
    public void test2(){
        String pathName = "d:\\a\\b\\c";
        File file = new File(pathName);
        boolean mkdir = file.mkdirs();
        System.out.println(mkdir?"创建成功":"创建失败");
    }
    //创建单个文件, 存在不会创建,不存在创建
    @Test
    public void test3(){
            String pathName = "d:\\1.txt";
            File file = new File(pathName);
            boolean newFile = file.delete();
            System.out.println(newFile?"创建成功":"创建失败");
        }
    // 查询文件是否存在    获取文件大小(字节)
    @Test
    public void test4(){
        String pathName = "d:\\1.txt";
        File file = new File(pathName);
        boolean exists = file.exists();
        System.out.println(exists?"文件存在":"文件不存在");
        //获取文件长度
        long length = file.length();
        System.out.println("长度是"+length);
        //获取文件名
        String name = file.getName();
        System.out.println(name);
        //获取path
        String path = file.getPath();
        System.out.println(path);
        //获取绝对路径
        String absolutePath = file.getAbsolutePath();
        System.out.println(absolutePath);
    }

}
posted @ 2021-01-24 10:49  dgxacc  阅读(51)  评论(0)    收藏  举报