由浅入深Netty基础知识NIO三大组件原理实战

Dear 丶 2024-03-22 18:42 155阅读 0赞

目录

  • 1 三大组件
    • 1.1 Channel & Buffer
    • 1.2 Selector
    • 1.3 多线程版设计
    • 1.4 多线程版缺点
    • 1.5 线程池版设计
    • 1.6 线程池版缺点
    • 1.7 selector 版设计
  • 2 ByteBuffer
    • 2.1 ByteBuffer 正确使用姿势
    • 2.2 ByteBuffer 结构
    • 2.3 调试工具类
    • 2.4 ByteBuffer 常见方法
      • 2.4.1 分配空间
      • 2.4.2 向 buffer 写入数据
      • 2.4.3 从 buffer 读取数据
      • 2.4.5 mark 和 reset
      • 2.4.6 字符串与 ByteBuffer 互转
    • 2.5 Buffer 的线程安全
    • 2.6 Scattering Reads
    • 2.7 Gathering Writes
    1. 文件编程
    • 3.1 FileChannel
    • 3.2 FileChannel 工作模式
      • 3.2.1 获取
      • 3.2.2 读取
      • 3.2.3 写入
      • 3.2.4 关闭
      • 3.2.5 位置
      • 3.2.6 大小
      • 3.2.7 强制写入
    • 3.3 两个 Channel 传输数据
    • 3.4 Path
    • 3.5 Files
    • 3.6 删除很危险

1 三大组件

在这里插入图片描述
non-blocking io 非阻塞 IO

1.1 Channel & Buffer

channel 有一点类似于 stream,它就是读写数据的双向通道,可以从 channel 将数据读入 buffer,也可以将 buffer 的数据写入 channel,而之前的 stream 要么是输入,要么是输出,channel 比 stream 更为底层

channel

buffer

常见的 Channel 有

  • FileChannel
  • DatagramChannel
  • SocketChannel
  • ServerSocketChannel

buffer 则用来缓冲读写数据,常见的 buffer 有

  • ByteBuffer

    • MappedByteBuffer
    • DirectByteBuffer
    • HeapByteBuffer
  • ShortBuffer
  • IntBuffer
  • LongBuffer
  • FloatBuffer
  • DoubleBuffer
  • CharBuffer

1.2 Selector

selector 单从字面意思不好理解,需要结合服务器的设计演化来理解它的用途

1.3 多线程版设计

多线程版

socket1

thread

socket2

thread

socket3

thread

1.4 多线程版缺点

  • 内存占用高
  • 线程上下文切换成本高
  • 只适合连接数少的场景

1.5 线程池版设计

线程池版

socket1

thread

socket2

thread

socket3

socket4

1.6 线程池版缺点

  • 阻塞模式下,线程仅能处理一个 socket 连接
  • 仅适合短连接场景

1.7 selector 版设计

selector 的作用就是配合一个线程来管理多个 channel,获取这些 channel 上发生的事件,这些 channel 工作在非阻塞模式下,不会让线程吊死在一个 channel 上。适合连接数特别多,但流量低的场景(low traffic)

selector 版

selector

thread

channel

channel

channel

调用 selector 的 select() 会阻塞直到 channel 发生了读写就绪事件,这些事件发生,select 方法就会返回这些事件交给 thread 来处理

2 ByteBuffer

有一普通文本文件 data.txt,内容为

  1. 1234567890abcd

使用 FileChannel 来读取文件内容

  1. @Slf4j
  2. public class ChannelDemo1 {
  3. public static void main(String[] args) {
  4. try (RandomAccessFile file = new RandomAccessFile("helloword/data.txt", "rw")) {
  5. FileChannel channel = file.getChannel();
  6. ByteBuffer buffer = ByteBuffer.allocate(10);
  7. do {
  8. // 向 buffer 写入
  9. int len = channel.read(buffer);
  10. log.debug("读到字节数:{}", len);
  11. if (len == -1) {
  12. break;
  13. }
  14. // 切换 buffer 读模式
  15. buffer.flip();
  16. while(buffer.hasRemaining()) {
  17. log.debug("{}", (char)buffer.get());
  18. }
  19. // 切换 buffer 写模式
  20. buffer.clear();
  21. } while (true);
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. }

输出

  1. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - 读到字节数:10
  2. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - 1
  3. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - 2
  4. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - 3
  5. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - 4
  6. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - 5
  7. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - 6
  8. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - 7
  9. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - 8
  10. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - 9
  11. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - 0
  12. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - 读到字节数:4
  13. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - a
  14. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - b
  15. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - c
  16. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - d
  17. 10:39:03 [DEBUG] [main] c.i.n.ChannelDemo1 - 读到字节数:-1

2.1 ByteBuffer 正确使用姿势

  1. 向 buffer 写入数据,例如调用 channel.read(buffer)
  2. 调用 flip() 切换至读模式
  3. 从 buffer 读取数据,例如调用 buffer.get()
  4. 调用 clear() 或 compact() 切换至写模式
  5. 重复 1~4 步骤

2.2 ByteBuffer 结构

ByteBuffer 有以下重要属性

  • capacity
  • position
  • limit

一开始

在这里插入图片描述

写模式下,position 是写入位置,limit 等于容量,下图表示写入了 4 个字节后的状态

在这里插入图片描述

flip 动作发生后,position 切换为读取位置,limit 切换为读取限制

在这里插入图片描述

读取 4 个字节后,状态

在这里插入图片描述

clear 动作发生后,状态

在这里插入图片描述

compact 方法,是把未读完的部分向前压缩,然后切换至写模式

在这里插入图片描述

2.3 调试工具类

  1. public class ByteBufferUtil {
  2. private static final char[] BYTE2CHAR = new char[256];
  3. private static final char[] HEXDUMP_TABLE = new char[256 * 4];
  4. private static final String[] HEXPADDING = new String[16];
  5. private static final String[] HEXDUMP_ROWPREFIXES = new String[65536 >>> 4];
  6. private static final String[] BYTE2HEX = new String[256];
  7. private static final String[] BYTEPADDING = new String[16];
  8. static {
  9. final char[] DIGITS = "0123456789abcdef".toCharArray();
  10. for (int i = 0; i < 256; i++) {
  11. HEXDUMP_TABLE[i << 1] = DIGITS[i >>> 4 & 0x0F];
  12. HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i & 0x0F];
  13. }
  14. int i;
  15. // Generate the lookup table for hex dump paddings
  16. for (i = 0; i < HEXPADDING.length; i++) {
  17. int padding = HEXPADDING.length - i;
  18. StringBuilder buf = new StringBuilder(padding * 3);
  19. for (int j = 0; j < padding; j++) {
  20. buf.append(" ");
  21. }
  22. HEXPADDING[i] = buf.toString();
  23. }
  24. // Generate the lookup table for the start-offset header in each row (up to 64KiB).
  25. for (i = 0; i < HEXDUMP_ROWPREFIXES.length; i++) {
  26. StringBuilder buf = new StringBuilder(12);
  27. buf.append(NEWLINE);
  28. buf.append(Long.toHexString(i << 4 & 0xFFFFFFFFL | 0x100000000L));
  29. buf.setCharAt(buf.length() - 9, '|');
  30. buf.append('|');
  31. HEXDUMP_ROWPREFIXES[i] = buf.toString();
  32. }
  33. // Generate the lookup table for byte-to-hex-dump conversion
  34. for (i = 0; i < BYTE2HEX.length; i++) {
  35. BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i);
  36. }
  37. // Generate the lookup table for byte dump paddings
  38. for (i = 0; i < BYTEPADDING.length; i++) {
  39. int padding = BYTEPADDING.length - i;
  40. StringBuilder buf = new StringBuilder(padding);
  41. for (int j = 0; j < padding; j++) {
  42. buf.append(' ');
  43. }
  44. BYTEPADDING[i] = buf.toString();
  45. }
  46. // Generate the lookup table for byte-to-char conversion
  47. for (i = 0; i < BYTE2CHAR.length; i++) {
  48. if (i <= 0x1f || i >= 0x7f) {
  49. BYTE2CHAR[i] = '.';
  50. } else {
  51. BYTE2CHAR[i] = (char) i;
  52. }
  53. }
  54. }
  55. /**
  56. * 打印所有内容
  57. * @param buffer
  58. */
  59. public static void debugAll(ByteBuffer buffer) {
  60. int oldlimit = buffer.limit();
  61. buffer.limit(buffer.capacity());
  62. StringBuilder origin = new StringBuilder(256);
  63. appendPrettyHexDump(origin, buffer, 0, buffer.capacity());
  64. System.out.println("+--------+-------------------- all ------------------------+----------------+");
  65. System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), oldlimit);
  66. System.out.println(origin);
  67. buffer.limit(oldlimit);
  68. }
  69. /**
  70. * 打印可读取内容
  71. * @param buffer
  72. */
  73. public static void debugRead(ByteBuffer buffer) {
  74. StringBuilder builder = new StringBuilder(256);
  75. appendPrettyHexDump(builder, buffer, buffer.position(), buffer.limit() - buffer.position());
  76. System.out.println("+--------+-------------------- read -----------------------+----------------+");
  77. System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), buffer.limit());
  78. System.out.println(builder);
  79. }
  80. private static void appendPrettyHexDump(StringBuilder dump, ByteBuffer buf, int offset, int length) {
  81. if (isOutOfBounds(offset, length, buf.capacity())) {
  82. throw new IndexOutOfBoundsException(
  83. "expected: " + "0 <= offset(" + offset + ") <= offset + length(" + length
  84. + ") <= " + "buf.capacity(" + buf.capacity() + ')');
  85. }
  86. if (length == 0) {
  87. return;
  88. }
  89. dump.append(
  90. " +-------------------------------------------------+" +
  91. NEWLINE + " | 0 1 2 3 4 5 6 7 8 9 a b c d e f |" +
  92. NEWLINE + "+--------+-------------------------------------------------+----------------+");
  93. final int startIndex = offset;
  94. final int fullRows = length >>> 4;
  95. final int remainder = length & 0xF;
  96. // Dump the rows which have 16 bytes.
  97. for (int row = 0; row < fullRows; row++) {
  98. int rowStartIndex = (row << 4) + startIndex;
  99. // Per-row prefix.
  100. appendHexDumpRowPrefix(dump, row, rowStartIndex);
  101. // Hex dump
  102. int rowEndIndex = rowStartIndex + 16;
  103. for (int j = rowStartIndex; j < rowEndIndex; j++) {
  104. dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
  105. }
  106. dump.append(" |");
  107. // ASCII dump
  108. for (int j = rowStartIndex; j < rowEndIndex; j++) {
  109. dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
  110. }
  111. dump.append('|');
  112. }
  113. // Dump the last row which has less than 16 bytes.
  114. if (remainder != 0) {
  115. int rowStartIndex = (fullRows << 4) + startIndex;
  116. appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);
  117. // Hex dump
  118. int rowEndIndex = rowStartIndex + remainder;
  119. for (int j = rowStartIndex; j < rowEndIndex; j++) {
  120. dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
  121. }
  122. dump.append(HEXPADDING[remainder]);
  123. dump.append(" |");
  124. // Ascii dump
  125. for (int j = rowStartIndex; j < rowEndIndex; j++) {
  126. dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
  127. }
  128. dump.append(BYTEPADDING[remainder]);
  129. dump.append('|');
  130. }
  131. dump.append(NEWLINE +
  132. "+--------+-------------------------------------------------+----------------+");
  133. }
  134. private static void appendHexDumpRowPrefix(StringBuilder dump, int row, int rowStartIndex) {
  135. if (row < HEXDUMP_ROWPREFIXES.length) {
  136. dump.append(HEXDUMP_ROWPREFIXES[row]);
  137. } else {
  138. dump.append(NEWLINE);
  139. dump.append(Long.toHexString(rowStartIndex & 0xFFFFFFFFL | 0x100000000L));
  140. dump.setCharAt(dump.length() - 9, '|');
  141. dump.append('|');
  142. }
  143. }
  144. public static short getUnsignedByte(ByteBuffer buffer, int index) {
  145. return (short) (buffer.get(index) & 0xFF);
  146. }
  147. }

2.4 ByteBuffer 常见方法

2.4.1 分配空间

可以使用 allocate 方法为 ByteBuffer 分配空间,其它 buffer 类也有该方法

  1. Bytebuffer buf = ByteBuffer.allocate(16);

2.4.2 向 buffer 写入数据

有两种办法

  • 调用 channel 的 read 方法
  • 调用 buffer 自己的 put 方法

    int readBytes = channel.read(buf);

  1. buf.put((byte)127);

2.4.3 从 buffer 读取数据

同样有两种办法

  • 调用 channel 的 write 方法
  • 调用 buffer 自己的 get 方法

    int writeBytes = channel.write(buf);

  1. byte b = buf.get();

get 方法会让 position 读指针向后走,如果想重复读取数据

  • 可以调用 rewind 方法将 position 重新置为 0
  • 或者调用 get(int i) 方法获取索引 i 的内容,它不会移动读指针

2.4.5 mark 和 reset

mark 是在读取时,做一个标记,即使 position 改变,只要调用 reset 就能回到 mark 的位置

注意

rewind 和 flip 都会清除 mark 位置

2.4.6 字符串与 ByteBuffer 互转

  1. ByteBuffer buffer1 = StandardCharsets.UTF_8.encode("你好");
  2. ByteBuffer buffer2 = Charset.forName("utf-8").encode("你好");
  3. debug(buffer1);
  4. debug(buffer2);
  5. CharBuffer buffer3 = StandardCharsets.UTF_8.decode(buffer1);
  6. System.out.println(buffer3.getClass());
  7. System.out.println(buffer3.toString());

输出

  1. +-------------------------------------------------+
  2. | 0 1 2 3 4 5 6 7 8 9 a b c d e f |
  3. +--------+-------------------------------------------------+----------------+
  4. |00000000| e4 bd a0 e5 a5 bd |...... |
  5. +--------+-------------------------------------------------+----------------+
  6. +-------------------------------------------------+
  7. | 0 1 2 3 4 5 6 7 8 9 a b c d e f |
  8. +--------+-------------------------------------------------+----------------+
  9. |00000000| e4 bd a0 e5 a5 bd |...... |
  10. +--------+-------------------------------------------------+----------------+
  11. class java.nio.HeapCharBuffer
  12. 你好

2.5 Buffer 的线程安全

Buffer 是非线程安全的

2.6 Scattering Reads

分散读取,有一个文本文件 3parts.txt

  1. onetwothree

使用如下方式读取,可以将数据填充至多个 buffer

  1. try (RandomAccessFile file = new RandomAccessFile("helloword/3parts.txt", "rw")) {
  2. FileChannel channel = file.getChannel();
  3. ByteBuffer a = ByteBuffer.allocate(3);
  4. ByteBuffer b = ByteBuffer.allocate(3);
  5. ByteBuffer c = ByteBuffer.allocate(5);
  6. channel.read(new ByteBuffer[]{
  7. a, b, c});
  8. a.flip();
  9. b.flip();
  10. c.flip();
  11. debug(a);
  12. debug(b);
  13. debug(c);
  14. } catch (IOException e) {
  15. e.printStackTrace();
  16. }

结果

  1. +-------------------------------------------------+
  2. | 0 1 2 3 4 5 6 7 8 9 a b c d e f |
  3. +--------+-------------------------------------------------+----------------+
  4. |00000000| 6f 6e 65 |one |
  5. +--------+-------------------------------------------------+----------------+
  6. +-------------------------------------------------+
  7. | 0 1 2 3 4 5 6 7 8 9 a b c d e f |
  8. +--------+-------------------------------------------------+----------------+
  9. |00000000| 74 77 6f |two |
  10. +--------+-------------------------------------------------+----------------+
  11. +-------------------------------------------------+
  12. | 0 1 2 3 4 5 6 7 8 9 a b c d e f |
  13. +--------+-------------------------------------------------+----------------+
  14. |00000000| 74 68 72 65 65 |three |
  15. +--------+-------------------------------------------------+----------------+

2.7 Gathering Writes

使用如下方式写入,可以将多个 buffer 的数据填充至 channel

  1. try (RandomAccessFile file = new RandomAccessFile("helloword/3parts.txt", "rw")) {
  2. FileChannel channel = file.getChannel();
  3. ByteBuffer d = ByteBuffer.allocate(4);
  4. ByteBuffer e = ByteBuffer.allocate(4);
  5. channel.position(11);
  6. d.put(new byte[]{
  7. 'f', 'o', 'u', 'r'});
  8. e.put(new byte[]{
  9. 'f', 'i', 'v', 'e'});
  10. d.flip();
  11. e.flip();
  12. debug(d);
  13. debug(e);
  14. channel.write(new ByteBuffer[]{
  15. d, e});
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }

输出

  1. +-------------------------------------------------+
  2. | 0 1 2 3 4 5 6 7 8 9 a b c d e f |
  3. +--------+-------------------------------------------------+----------------+
  4. |00000000| 66 6f 75 72 |four |
  5. +--------+-------------------------------------------------+----------------+
  6. +-------------------------------------------------+
  7. | 0 1 2 3 4 5 6 7 8 9 a b c d e f |
  8. +--------+-------------------------------------------------+----------------+
  9. |00000000| 66 69 76 65 |five |
  10. +--------+-------------------------------------------------+----------------+

文件内容

  1. onetwothreefourfive

3. 文件编程

3.1 FileChannel

3.2 FileChannel 工作模式

FileChannel 只能工作在阻塞模式下

3.2.1 获取

不能直接打开 FileChannel,必须通过 FileInputStream、FileOutputStream 或者 RandomAccessFile 来获取 FileChannel,它们都有 getChannel 方法

  • 通过 FileInputStream 获取的 channel 只能读
  • 通过 FileOutputStream 获取的 channel 只能写
  • 通过 RandomAccessFile 是否能读写根据构造 RandomAccessFile 时的读写模式决定

3.2.2 读取

会从 channel 读取数据填充 ByteBuffer,返回值表示读到了多少字节,-1 表示到达了文件的末尾

  1. int readBytes = channel.read(buffer);

3.2.3 写入

写入的正确姿势如下, SocketChannel

  1. ByteBuffer buffer = ...;
  2. buffer.put(...); // 存入数据
  3. buffer.flip(); // 切换读模式
  4. while(buffer.hasRemaining()) {
  5. channel.write(buffer);
  6. }

在 while 中调用 channel.write 是因为 write 方法并不能保证一次将 buffer 中的内容全部写入 channel

3.2.4 关闭

channel 必须关闭,不过调用了 FileInputStream、FileOutputStream 或者 RandomAccessFile 的 close 方法会间接地调用 channel 的 close 方法

3.2.5 位置

获取当前位置

  1. long pos = channel.position();

设置当前位置

  1. long newPos = ...;
  2. channel.position(newPos);

设置当前位置时,如果设置为文件的末尾

  • 这时读取会返回 -1
  • 这时写入,会追加内容,但要注意如果 position 超过了文件末尾,再写入时在新内容和原末尾之间会有空洞(00)

3.2.6 大小

使用 size 方法获取文件的大小

3.2.7 强制写入

操作系统出于性能的考虑,会将数据缓存,不是立刻写入磁盘。可以调用 force(true) 方法将文件内容和元数据(文件的权限等信息)立刻写入磁盘

3.3 两个 Channel 传输数据

  1. String FROM = "helloword/data.txt";
  2. String TO = "helloword/to.txt";
  3. long start = System.nanoTime();
  4. try (FileChannel from = new FileInputStream(FROM).getChannel();
  5. FileChannel to = new FileOutputStream(TO).getChannel();
  6. ) {
  7. from.transferTo(0, from.size(), to);
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. long end = System.nanoTime();
  12. System.out.println("transferTo 用时:" + (end - start) / 1000_000.0);

输出

  1. transferTo 用时:8.2011

超过 2g 大小的文件传输

  1. public class TestFileChannelTransferTo {
  2. public static void main(String[] args) {
  3. try (
  4. FileChannel from = new FileInputStream("data.txt").getChannel();
  5. FileChannel to = new FileOutputStream("to.txt").getChannel();
  6. ) {
  7. // 效率高,底层会利用操作系统的零拷贝进行优化
  8. long size = from.size();
  9. // left 变量代表还剩余多少字节
  10. for (long left = size; left > 0; ) {
  11. System.out.println("position:" + (size - left) + " left:" + left);
  12. left -= from.transferTo((size - left), left, to);
  13. }
  14. } catch (IOException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. }

实际传输一个超大文件

  1. position:0 left:7769948160
  2. position:2147483647 left:5622464513
  3. position:4294967294 left:3474980866
  4. position:6442450941 left:1327497219

3.4 Path

jdk7 引入了 Path 和 Paths 类

  • Path 用来表示文件路径
  • Paths 是工具类,用来获取 Path 实例

    Path source = Paths.get(“1.txt”); // 相对路径 使用 user.dir 环境变量来定位 1.txt

    Path source = Paths.get(“d:\1.txt”); // 绝对路径 代表了 d:\1.txt

    Path source = Paths.get(“d:/1.txt”); // 绝对路径 同样代表了 d:\1.txt

    Path projects = Paths.get(“d:\data”, “projects”); // 代表了 d:\data\projects

  • . 代表了当前路径

  • .. 代表了上一级路径

例如目录结构如下

  1. d:
  2. |- data
  3. |- projects
  4. |- a
  5. |- b

代码

  1. Path path = Paths.get("d:\\data\\projects\\a\\..\\b");
  2. System.out.println(path);
  3. System.out.println(path.normalize()); // 正常化路径

会输出

  1. d:\data\projects\a\..\b
  2. d:\data\projects\b

3.5 Files

检查文件是否存在

  1. Path path = Paths.get("helloword/data.txt");
  2. System.out.println(Files.exists(path));

创建一级目录

  1. Path path = Paths.get("helloword/d1");
  2. Files.createDirectory(path);
  • 如果目录已存在,会抛异常 FileAlreadyExistsException
  • 不能一次创建多级目录,否则会抛异常 NoSuchFileException

创建多级目录用

  1. Path path = Paths.get("helloword/d1/d2");
  2. Files.createDirectories(path);

拷贝文件

  1. Path source = Paths.get("helloword/data.txt");
  2. Path target = Paths.get("helloword/target.txt");
  3. Files.copy(source, target);
  • 如果文件已存在,会抛异常 FileAlreadyExistsException

如果希望用 source 覆盖掉 target,需要用 StandardCopyOption 来控制

  1. Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);

移动文件

  1. Path source = Paths.get("helloword/data.txt");
  2. Path target = Paths.get("helloword/data.txt");
  3. Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
  • StandardCopyOption.ATOMIC_MOVE 保证文件移动的原子性

删除文件

  1. Path target = Paths.get("helloword/target.txt");
  2. Files.delete(target);
  • 如果文件不存在,会抛异常 NoSuchFileException

删除目录

  1. Path target = Paths.get("helloword/d1");
  2. Files.delete(target);
  • 如果目录还有内容,会抛异常 DirectoryNotEmptyException

遍历目录文件

  1. public static void main(String[] args) throws IOException {
  2. Path path = Paths.get("C:\\Program Files\\Java\\jdk1.8.0_91");
  3. AtomicInteger dirCount = new AtomicInteger();
  4. AtomicInteger fileCount = new AtomicInteger();
  5. Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
  6. @Override
  7. public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
  8. throws IOException {
  9. System.out.println(dir);
  10. dirCount.incrementAndGet();
  11. return super.preVisitDirectory(dir, attrs);
  12. }
  13. @Override
  14. public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
  15. throws IOException {
  16. System.out.println(file);
  17. fileCount.incrementAndGet();
  18. return super.visitFile(file, attrs);
  19. }
  20. });
  21. System.out.println(dirCount); // 133
  22. System.out.println(fileCount); // 1479
  23. }

统计 jar 的数目

  1. Path path = Paths.get("C:\\Program Files\\Java\\jdk1.8.0_91");
  2. AtomicInteger fileCount = new AtomicInteger();
  3. Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
  4. @Override
  5. public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
  6. throws IOException {
  7. if (file.toFile().getName().endsWith(".jar")) {
  8. fileCount.incrementAndGet();
  9. }
  10. return super.visitFile(file, attrs);
  11. }
  12. });
  13. System.out.println(fileCount); // 724

删除多级目录

  1. Path path = Paths.get("d:\\a");
  2. Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
  3. @Override
  4. public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
  5. throws IOException {
  6. Files.delete(file);
  7. return super.visitFile(file, attrs);
  8. }
  9. @Override
  10. public FileVisitResult postVisitDirectory(Path dir, IOException exc)
  11. throws IOException {
  12. Files.delete(dir);
  13. return super.postVisitDirectory(dir, exc);
  14. }
  15. });

3.6 删除很危险

删除是危险操作,确保要递归删除的文件夹没有重要内容

拷贝多级目录

  1. long start = System.currentTimeMillis();
  2. String source = "D:\\Snipaste-1.16.2-x64";
  3. String target = "D:\\Snipaste-1.16.2-x64aaa";
  4. Files.walk(Paths.get(source)).forEach(path -> {
  5. try {
  6. String targetName = path.toString().replace(source, target);
  7. // 是目录
  8. if (Files.isDirectory(path)) {
  9. Files.createDirectory(Paths.get(targetName));
  10. }
  11. // 是普通文件
  12. else if (Files.isRegularFile(path)) {
  13. Files.copy(path, Paths.get(targetName));
  14. }
  15. } catch (IOException e) {
  16. e.printStackTrace();
  17. }
  18. });
  19. long end = System.currentTimeMillis();
  20. System.out.println(end - start);

发表评论

表情:
评论列表 (有 0 条评论,155人围观)

还没有评论,来说两句吧...

相关阅读