当前位置: 首页 > news >正文

java.nio 包详解

java.nio(New I/O)是 Java 1.4 引入的高性能 I/O API,提供了比传统 java.io 更高效的 I/O 操作方式,特别适合处理大量数据和高并发场景。


核心组件

1. 缓冲区(Buffers)

核心类

  • ByteBufferCharBufferShortBufferIntBufferLongBufferFloatBufferDoubleBuffer

  • MappedByteBuffer(内存映射文件缓冲区)

基本用法

// 创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);  // 堆缓冲区
ByteBuffer directBuffer = ByteBuffer.allocateDirect(1024);  // 直接缓冲区// 写入数据
buffer.put((byte)1);
buffer.putInt(123);
buffer.putDouble(3.14);// 切换为读模式
buffer.flip();// 读取数据
byte b = buffer.get();
int i = buffer.getInt();
double d = buffer.getDouble();// 清空缓冲区
buffer.clear();

缓冲区状态属性

  • capacity:缓冲区容量

  • position:当前位置

  • limit:读写限制

  • mark:标记位置

2. 通道(Channels)

核心通道类

  • FileChannel:文件通道

  • SocketChannelServerSocketChannel:TCP 通道

  • DatagramChannel:UDP 通道

  • Pipe.SinkChannelPipe.SourceChannel:管道通道

文件通道示例

// 文件读取
try (FileChannel channel = FileChannel.open(Paths.get("file.txt"), StandardOpenOption.READ)) {ByteBuffer buffer = ByteBuffer.allocate(1024);while (channel.read(buffer) > 0) {buffer.flip();// 处理数据buffer.clear();}
}// 文件写入
try (FileChannel channel = FileChannel.open(Paths.get("file.txt"), StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {ByteBuffer buffer = ByteBuffer.wrap("Hello NIO".getBytes());channel.write(buffer);
}

3. 选择器(Selectors)

用于非阻塞 I/O 的多路复用:

Selector selector = Selector.open();
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.bind(new InetSocketAddress(8080));
serverChannel.register(selector, SelectionKey.OP_ACCEPT);while (true) {selector.select();Set<SelectionKey> selectedKeys = selector.selectedKeys();Iterator<SelectionKey> iter = selectedKeys.iterator();while (iter.hasNext()) {SelectionKey key = iter.next();if (key.isAcceptable()) {// 处理新连接SocketChannel client = serverChannel.accept();client.configureBlocking(false);client.register(selector, SelectionKey.OP_READ);} else if (key.isReadable()) {// 处理读取SocketChannel client = (SocketChannel) key.channel();ByteBuffer buffer = ByteBuffer.allocate(1024);client.read(buffer);// 处理数据}iter.remove();}
}

高级特性

1. 内存映射文件(Memory-Mapped Files)

try (FileChannel channel = FileChannel.open(Paths.get("largefile.dat"), StandardOpenOption.READ)) {MappedByteBuffer mappedBuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());// 直接操作内存映射区域while (mappedBuffer.hasRemaining()) {byte b = mappedBuffer.get();}
}

2. 文件锁定

try (FileChannel channel = FileChannel.open(Paths.get("file.txt"), StandardOpenOption.WRITE)) {// 排他锁FileLock lock = channel.lock();try {// 执行写操作channel.write(ByteBuffer.wrap("Data".getBytes()));} finally {lock.release();}// 共享锁(只读)FileLock sharedLock = channel.lock(0, Long.MAX_VALUE, true);
}

3. 分散/聚集 I/O(Scatter/Gather)

// 分散读取
ByteBuffer header = ByteBuffer.allocate(128);
ByteBuffer body = ByteBuffer.allocate(1024);
ByteBuffer[] buffers = {header, body};
channel.read(buffers);// 聚集写入
header.flip();
body.flip();
channel.write(buffers);

4. 文件系统操作

java.nio.file 包(NIO.2,Java 7 引入)提供了更强大的文件系统操作:

Path path = Paths.get("/path/to/file");
Files.createDirectories(path.getParent());
Files.write(path, "content".getBytes(), StandardOpenOption.CREATE);// 遍历目录
try (Stream<Path> stream = Files.list(Paths.get("/tmp"))) {stream.forEach(System.out::println);
}// 文件监控
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get("/path/to/watch");
dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);

性能优势

  1. 非阻塞 I/O:允许单线程管理多个通道

  2. 内存映射:直接操作文件内存映射,避免系统调用

  3. 直接缓冲区:减少 JVM 堆与本地内存间的数据拷贝

  4. 零拷贝:通过 FileChannel.transferTo/transferFrom 实现

与传统 I/O 对比

特性java.iojava.nio
数据流流式基于缓冲区
阻塞模式阻塞可选非阻塞
多连接处理每个连接一个线程单线程多路复用
性能适合少量连接适合高并发
API 复杂度简单较复杂

最佳实践

  1. 大文件处理:优先使用内存映射文件

  2. 高并发网络:使用 Selector 实现非阻塞 I/O

  3. 频繁 I/O 操作:使用直接缓冲区减少拷贝

  4. 资源释放:确保关闭通道和选择器

  5. 异常处理:妥善处理 IOException 和 ClosedChannelException


总结

java.nio 包提供了:

  • 基于缓冲区的 I/O 操作

  • 非阻塞 I/O 支持

  • 内存映射文件功能

  • 高效的文件和网络操作

  • 更灵活的文件系统接口(NIO.2)

虽然学习曲线比传统 I/O 更陡峭,但在处理高性能 I/O 需求时,NIO 通常是更好的选择。对于简单文件操作,可以结合使用 java.nio.file 包提供的便捷方法。

http://www.dtcms.com/a/499156.html

相关文章:

  • python+django/flask婚纱摄影拍照管理系统
  • SpringBoot 集成 ELK 实现系统操作日志存储方案
  • 如何解决 Jacob 与 Tomcat 类加载问题:深入分析 Tomcat 类加载机制与 JVM 双亲委派机制
  • AVL树(平衡二叉树)详细介绍与Java实现
  • 2025年市场岗位能力重构与跨领域转型路径分析
  • SQL UNIQUE约束详解
  • 【unity实战】MapMagic 2实战例子
  • 系统找不到文件
  • 网站建设综合实训总结有谁会设制网站
  • 什么是Redis的缓存问题,以及如何解决
  • Python遗传算法详解:从理论到实践
  • 技术支持 东莞网站建设 轴承信宜网站建设公司
  • CSS基础知识(3)
  • git分支管理介绍和stash命令
  • 建个网站视频教程团队拓展训练感悟
  • 做网站应选那个主题龙岩微信小程序定制
  • Linux学习笔记--GPIO子系统和PinCtrl子系统
  • SpringBoot外部配置打包
  • 通达信--超级盘口
  • 基于单片机的开尔文电路电阻测量WIFI上传设计
  • 矽塔 SA8210 输入耐压36V 6A过流保护阈值 过压/过流保护芯片 SOT23-6/DFN2X2-8
  • 永年做网站收集链接 做网站
  • Linux----权限
  • 深入理解 PHP 框架里的设计模式
  • 西安网站工作室做外贸网站哪家的好
  • 如何用python写一个有字数上限的文字区块链?
  • 算能 CV184 智能相机整体方案介绍
  • 广州皮具网站建设湖南手机版建站系统信息
  • 大型网站建设哪里济南兴田德润实惠吗临沂市网站建设公司
  • Linux系统:线程介绍与POSIX线程库实现线程控制