教程中心 / Java教程 / NIO

NIO

15分钟 I/O流

NIO与IO的区别

特性IONIO
模型流式IO缓冲区IO
阻塞阻塞IO非阻塞IO
选择器Selector

Path路径

 Path path = Paths.get("folder", "file.txt");
path.toAbsolutePath();
path.getFileName();
path.getParent(); 

Files操作

 byte[] data = Files.readAllBytes(path);
List lines = Files.readAllLines(path);
Files.write(path, data);

Files.copy(source, target);
Files.move(source, target);
Files.delete(path); 

Buffer缓冲区

 ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("Hello".getBytes());
buffer.flip();
byte[] arr = new byte[buffer.remaining()];
buffer.get(arr); 

小结

  • NIO基于缓冲区(Buffer)操作
  • Path替代File表示路径
  • Files提供便捷文件操作方法
  • Channel支持非阻塞操作
☕ Java 在线代码编辑器
📝 运行结果