使用 Files 操作文件

查看

  1. Path path = Paths.get(System.getProperty("user.dir")
  2. + "/jdk8Test/src/main/resources/file.txt");
  3. // 查看文件大小
  4. Files.size(path);

写入

  1. Path path = Paths.get(System.getProperty("user.dir")
  2. + "/jdk8Test/src/main/resources/file.txt");
  3. // 写数据
  4. int writeCount = 100;
  5. List<String> info = IntStream.rangeClosed(0, writeCount)
  6. .parallel()
  7. .mapToObj(e -> "content" + e).collect(Collectors.toList());
  8. Files.write(path, info);

查询

  1. int readCount = 20;
  2. // 2.1 读取
  3. List<String> collect = Files.lines(path).limit(readCount).collect(Collectors.toList());
  4. System.out.println(collect);
  5. // 2.2 跳过读取
  6. collect = Files.lines(path).skip(readCount).limit(readCount).collect(Collectors.toList());
  7. System.out.println(collect);
  8. // 3. 记录行数
  9. AtomicLong atomicLong = new AtomicLong(0L);
  10. Files.lines(path).forEach(e -> {
  11. atomicLong.incrementAndGet();
  12. });
  13. System.out.println(atomicLong.get());

使用 Files 类静态方法进行文件操作注意释放文件句柄

  1. // 1 Too many open files
  2. // 并没有复现
  3. LongAdder longAdder = new LongAdder();
  4. LongAdder finalLongAdder = longAdder;
  5. IntStream.rangeClosed(1, 1000).forEach(i -> {
  6. try {
  7. Files.lines(path).forEach(line -> finalLongAdder.increment());
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. });
  12. // 2 用 try with resources 包裹
  13. longAdder = new LongAdder();
  14. LongAdder finalLongAdder1 = longAdder;
  15. IntStream.rangeClosed(1, 1000).forEach(i -> {
  16. // try with resources
  17. try (Stream<String> lines = Files.lines(path)) {
  18. lines.forEach(line -> finalLongAdder1.increment());
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. });

复制

  • 使用 BufferedXXX 进行文件复制
  • 也可以使用 FileChannel ```java Path path = Paths.get(System.getProperty(“user.dir”)
    1. + "/jdk8Test/src/main/resources/file.txt");
    Path pathTo = Paths.get(System.getProperty(“user.dir”)
    1. + "/jdk8Test/src/main/resources/file2.txt");

// 文件复制 FileChannel in = FileChannel.open(path); FileChannel out = FileChannel.open(pathTo, StandardOpenOption.CREATE, StandardOpenOption.WRITE); in.transferTo(0, in.size(), out); ```

BufferedXXX 的意义

  1. 内部维护一个 8kb 的缓冲区,应对不一样的场景
    1. 避免单字节读取的缓慢
    2. 避免应对未知大小数据时,如何取舍缓冲区的大小(反正就是用了就稳定有缓冲区了)