Files类的常用方法

1.Files.exists() 检查文件路径是否存在

    public static void main(String[] args) {
        Path path = Paths.get("E:/TXT游戏表.txt");
        Boolean fileboolean = Files.exists(path,new LinkOption[]{ LinkOption.NOFOLLOW_LINKS});
        System.out.println(fileboolean);
    }
true

通过这个方法判定文件是否存在时,首先得指定一个path路径,默认情况下符号链接会被追踪。
第二个参数是一个LinkOption数组,决定文件是否存在。LinkOption.NOFOLLOW_LINKS表明不追踪符号链接。如果目录或文件存在,则返回true,如果目录或文件不存在或者不知道其存在性,则返回false。
2.Files.createFile() 创建文件

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("E:/Demo.txt");
        Files.createFile(path);
    }

3.Files.createDirectory() 创建文件夹

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("E:/Demo");
        Files.createDirectory(path);
    }

4.Files.delete() 删除一个文件或者目录

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("E:/Demo");
        Files.delete(path);
    }

5.Files.copy()复制文件

    public static void main(String[] args) throws IOException {
        Path path1 = Paths.get("E:/Demo01.txt");
        Path path2 = Paths.get("E:/Demo02.txt");
        Files.copy(path1,path2);//把path1复制到path2中
    }

6.Files.move() 移动文件

    public static void main(String[] args) throws IOException {
        Path path1 = Paths.get("E:/Demo01.txt");
        Path path3 = Paths.get("E:/Demo03.txt");
        Files.move(path1,path3);//将path1移动并修改为Demo03.txt
    }

7.Files.size() 查看文件个数

    public static void main(String[] args) throws IOException {
        Path path1 = Paths.get("E:/Demo02.txt");
        System.out.println(Files.size(path1));
    }

猜你喜欢

转载自blog.csdn.net/weixin_44168355/article/details/90212371