Java nio 文件操作 Path,Files类详解一

来源:互联网 发布:网络剧广告植入 编辑:程序博客网 时间:2024/05/21 06:02

Path 类是jdk7新增加的特性之一,用来代替java.io.File类。
之所以新增这个类,是由于java.io.File类有很多缺陷:
1.java.io.File类里面很多方法失败时没有异常处理,或抛出异常
java.io.File.delete()方法返回一个布尔值指示成功或失败但是没有失败原因
2.Path 速度快,方便。

Path 操作

1.删除文件
这里写图片描述
2.遍历目录,不包括子目录的文件

    Path dir = Paths.get("F:\\LZ\\pdf");    DirectoryStream<Path> stream = Files.newDirectoryStream(dir);    for(Path path : stream){        System.out.println(path.getFileName());    }

2.遍历目录,及其子目录下的文件

    Path dir = Paths.get("F:\\LZ\\pdf");    Files.walkFileTree(dir,new SimpleFileVisitor<Path>(){        @Override        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)                throws IOException {            if(file.toString().endsWith(".pdf")){                System.out.println(file.getFileName());            }            return super.visitFile(file, attrs);        }    });

3.创建多级目录

    Path dir = Paths.get("F:\\LZ\\xx\\dd");    Files.createDirectories(dir);

4.创建文件, 不存在则抛出异常

    Path dir = Paths.get("F:\\LZ\\xx\\dd\\1.txt");    Files.createFile(dir);

5.文件的复制

    Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");    Path target = Paths.get("F:\\LZ\\xx\\dd\\2.txt");    //REPLACE_EXISTING:文件存在,就替换    Files.copy(src, target,StandardCopyOption.REPLACE_EXISTING);

6.一行一行读取文件

    Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");    BufferedReader reader = Files.newBufferedReader(src,StandardCharsets.UTF_8);    String line ;    while((line=reader.readLine()) != null){        System.out.println(line);    }    reader.close();

7.写入字符串

    Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");    BufferedWriter writer = Files.newBufferedWriter(src, StandardCharsets.UTF_8            ,StandardOpenOption.APPEND); // 追加    writer.write("hello word Path");    writer.close();

8.二进制 读写 与字符串类似

  1. 一个方法直接去取字符串 和 二进制流
    // 字符串    Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");    for(String line : Files.readAllLines(src)){        System.out.println(line);    }    // 二进制流    byte[] bytes = Files.readAllBytes(src);

10.监测是否 目录下的 文件,目录 被修改,创建,或删除.
这里写图片描述

11.读取文件的 最后 1000 个字符
这里写图片描述

1 0