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

Java IO与NIO的对比与高级用法

在Java中,I/O操作(输入/输出操作)是非常基础且重要的一部分。Java提供了两种主要的I/O API:传统的IO(java.io包)和新IO(NIO,java.nio包)。这两者在设计理念、性能和使用场景上有显著的不同。本文将深入探讨Java IO与NIO的对比,并提供一些高级用法的示例代码。

1. Java IO与NIO的基本概念
1.1 Java IO

Java IO API是基于流(Stream)的模型。它以同步和阻塞的方式进行数据读写操作。每次I/O操作都会阻塞调用线程,直到操作完成。这种方式简单直观,但在高并发场景下性能表现不佳。

1.2 Java NIO

Java NIO(Non-blocking IO)引入了一种基于缓冲区(Buffer)和通道(Channel)的模型。NIO支持非阻塞模式,可以在进行I/O操作时不中断线程,从而提高了性能和可扩展性。NIO还引入了选择器(Selector)用于管理多个通道的非阻塞I/O操作。

2. Java IO与NIO的对比
特性Java IOJava NIO
模型基于流 (Stream)基于缓冲区 (Buffer) 和通道 (Channel)
阻塞/非阻塞阻塞I/O非阻塞I/O
数据处理字节/字符流缓冲区中读取和写入数据
性能简单,但在高并发下性能较差在高并发和大数据处理场景下性能更佳
API复杂度较为简单复杂度较高
3. Java IO的高级用法
3.1 文件读写操作
import java.io.*;public class FileIODemo {public static void main(String[] args) {String filePath = "example.txt";try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {writer.write("Hello, Java IO!");} catch (IOException e) {e.printStackTrace();}try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {String line;while ((line = reader.readLine()) != null) {System.out.println(line);}} catch (IOException e) {e.printStackTrace();}}
}
3.2 网络通信(Socket编程)
import java.io.*;
import java.net.*;public class SocketIODemo {public static void main(String[] args) {// Servernew Thread(() -> {try (ServerSocket serverSocket = new ServerSocket(8080)) {Socket socket = serverSocket.accept();BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);writer.println("Hello, Client!");System.out.println("Client says: " + reader.readLine());} catch (IOException e) {e.printStackTrace();}}).start();// Clientnew Thread(() -> {try (Socket socket = new Socket("localhost", 8080)) {BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);System.out.println("Server says: " + reader.readLine());writer.println("Hello, Server!");} catch (IOException e) {e.printStackTrace();}}).start();}
}
4. Java NIO的高级用法
4.1 文件读写操作
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;public class FileNIODemo {public static void main(String[] args) {String filePath = "example_nio.txt";Path path = Paths.get(filePath);String content = "Hello, Java NIO!";// Write to file using NIOtry (FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {ByteBuffer buffer = ByteBuffer.allocate(1024);buffer.put(content.getBytes());buffer.flip();fileChannel.write(buffer);} catch (IOException e) {e.printStackTrace();}// Read from file using NIOtry (FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ)) {ByteBuffer buffer = ByteBuffer.allocate(1024);fileChannel.read(buffer);buffer.flip();byte[] bytes = new byte[buffer.remaining()];buffer.get(bytes);System.out.println(new String(bytes));} catch (IOException e) {e.printStackTrace();}}
}
4.2 网络通信(Socket编程)
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;public class SocketNIODemo {public static void main(String[] args) {new Thread(SocketNIODemo::startServer).start();new Thread(SocketNIODemo::startClient).start();}public static void startServer() {try (Selector selector = Selector.open();ServerSocketChannel serverChannel = ServerSocketChannel.open()) {serverChannel.bind(new InetSocketAddress(8081));serverChannel.configureBlocking(false);serverChannel.register(selector, SelectionKey.OP_ACCEPT);while (true) {selector.select();Iterator<SelectionKey> keys = selector.selectedKeys().iterator();while (keys.hasNext()) {SelectionKey key = keys.next();keys.remove();if (key.isAcceptable()) {ServerSocketChannel server = (ServerSocketChannel) key.channel();SocketChannel client = server.accept();client.configureBlocking(false);client.register(selector, SelectionKey.OP_READ);ByteBuffer buffer = ByteBuffer.wrap("Hello, Client!".getBytes());client.write(buffer);} else if (key.isReadable()) {SocketChannel client = (SocketChannel) key.channel();ByteBuffer buffer = ByteBuffer.allocate(256);client.read(buffer);buffer.flip();byte[] bytes = new byte[buffer.remaining()];buffer.get(bytes);System.out.println("Client says: " + new String(bytes));}}}} catch (IOException e) {e.printStackTrace();}}public static void startClient() {try (SocketChannel clientChannel = SocketChannel.open(new InetSocketAddress("localhost", 8081))) {clientChannel.configureBlocking(false);ByteBuffer buffer = ByteBuffer.allocate(256);while (clientChannel.read(buffer) <= 0) {// Wait for server response}buffer.flip();byte[] bytes = new byte[buffer.remaining()];buffer.get(bytes);System.out.println("Server says: " + new String(bytes));buffer.clear();buffer.put("Hello, Server!".getBytes());buffer.flip();while (buffer.hasRemaining()) {clientChannel.write(buffer);}} catch (IOException e) {e.printStackTrace();}}
}
5. 结论

Java IO和NIO各有优缺点,在具体应用中应根据需求选择合适的API。传统的IO适合简单、低并发的场景,而NIO在高并发、大数据处理的场景中表现更佳。希望本文通过详细的对比和代码示例,能帮助读者更好地理解Java IO与NIO的区别与应用。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • python-打分(赛氪OJ)
  • 书生大模型实战营第三期——入门岛——Git基础知识
  • 【Android】四大组件(Activity、Service、Broadcast Receiver、Content Provider)、结构目录
  • DataX迁移数据到StarRocks超大表报too many version问题记录
  • 深度学习入门(二):常见概念(重点:泛化误差)
  • 电销机器人有哪些优势?
  • 【python基础】python基础习题练习(一)
  • C++ 依赖倒置
  • 【C++】STL | string 详解及重要函数的实现
  • 项目中万能使用tailwindcss,无版本冲突、报错
  • 中小微企业必看:税贷票贷融资策略与实战技巧
  • 最新消息:Sedex 供应商会员年费调整
  • Pytest测试报告生成专题
  • 客户三要素和五要素
  • dp+容斥原理,LeetCode 3130. 找出所有稳定的二进制数组 II
  • 《Java编程思想》读书笔记-对象导论
  • 0x05 Python数据分析,Anaconda八斩刀
  • github指令
  • java中具有继承关系的类及其对象初始化顺序
  • laravel with 查询列表限制条数
  • python 装饰器(一)
  • React 快速上手 - 06 容器组件、展示组件、操作组件
  • Spring Cloud中负载均衡器概览
  • SwizzleMethod 黑魔法
  • Zepto.js源码学习之二
  • 官方新出的 Kotlin 扩展库 KTX,到底帮你干了什么?
  • 函数式编程与面向对象编程[4]:Scala的类型关联Type Alias
  • 前嗅ForeSpider教程:创建模板
  • 如何邀请好友注册您的网站(模拟百度网盘)
  • 协程
  • 远离DoS攻击 Windows Server 2016发布DNS政策
  • 正则表达式小结
  • ​ArcGIS Pro 如何批量删除字段
  • ​Redis 实现计数器和限速器的
  • ​无人机石油管道巡检方案新亮点:灵活准确又高效
  • # Maven错误Error executing Maven
  • #我与Java虚拟机的故事#连载06:收获颇多的经典之作
  • $con= MySQL有关填空题_2015年计算机二级考试《MySQL》提高练习题(10)
  • (4)Elastix图像配准:3D图像
  • (4)事件处理——(7)简单事件(Simple events)
  • (7)摄像机和云台
  • (C#)Windows Shell 外壳编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令...
  • (day6) 319. 灯泡开关
  • (pytorch进阶之路)扩散概率模型
  • (附源码)python房屋租赁管理系统 毕业设计 745613
  • (附源码)springboot宠物管理系统 毕业设计 121654
  • (论文阅读30/100)Convolutional Pose Machines
  • (每日持续更新)jdk api之FileFilter基础、应用、实战
  • (自用)learnOpenGL学习总结-高级OpenGL-抗锯齿
  • .bat批处理(五):遍历指定目录下资源文件并更新
  • .NET CF命令行调试器MDbg入门(二) 设备模拟器
  • .net core docker部署教程和细节问题
  • .net core 源码_ASP.NET Core之Identity源码学习
  • .NET Framework Client Profile - a Subset of the .NET Framework Redistribution
  • .NET Framework杂记