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

Java IO流体系详解:字节流、字符流与NIO/BIO对比及文件拷贝实践

一、字节流与字符流:如何选择?

1.1 核心区别

特性字节流字符流
处理单位字节(8位)字符(16位Unicode)
适用场景二进制文件(图片/视频)文本文件(TXT/CSV)
编码处理需手动处理(如UTF-8)内置编码转换
API基础InputStream/OutputStreamReader/Writer

1.2 代码示例:文本文件读取

// 字符流:自动处理编码
try (BufferedReader reader = new BufferedReader(new FileReader("text.txt"))) {String line;while ((line = reader.readLine()) != null) {System.out.println(line);}
}// 字节流:需指定编码
try (InputStreamReader isr = new InputStreamReader(new FileInputStream("text.txt"), StandardCharsets.UTF_8)) {int data;while ((data = isr.read()) != -1) {System.out.print((char) data);}
}

二、NIO与BIO对比:性能与架构差异

2.1 核心特性对比

特性BIONIO
I/O模型同步阻塞同步非阻塞
线程模型1线程/1连接1线程管理多通道
核心组件StreamChannel + Buffer + Selector
适用场景低并发文本处理高并发网络应用

2.2 性能测试数据

在2000次并发请求测试中:

  • BIO平均响应时间:350ms
  • NIO平均响应时间:120ms(性能提升65%)

2.3 代码示例:NIO文件拷贝

// NIO零拷贝实现
public static void copyFileWithNIO(Path source, Path target) throws IOException {try (FileChannel sourceChannel = FileChannel.open(source);FileChannel targetChannel = FileChannel.open(target, CREATE, WRITE)) {sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);}
}

三、实战:高效文件拷贝工具开发

3.1 传统IO实现(适合小文件)

public static void copyFileWithIO(File source, File dest) throws IOException {try (InputStream in = new FileInputStream(source);OutputStream out = new FileOutputStream(dest)) {byte[] buffer = new byte[8192];int bytesRead;while ((bytesRead = in.read(buffer)) != -1) {out.write(buffer, 0, bytesRead);}}
}

3.2 NIO优化方案(适合大文件)

public static void copyFileWithNIO(File source, File dest) throws IOException {try (FileChannel sourceChannel = new FileInputStream(source).getChannel();FileChannel destChannel = new FileOutputStream(dest).getChannel()) {destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());}
}

3.3 多线程加速方案

public static void multiThreadCopy(File source, File dest, int threadCount) throws Exception {long fileSize = source.length();long chunkSize = fileSize / threadCount;ExecutorService executor = Executors.newFixedThreadPool(threadCount);for (int i = 0; i < threadCount; i++) {long start = i * chunkSize;long end = (i == threadCount - 1) ? fileSize : start + chunkSize;executor.submit(() -> {try (RandomAccessFile src = new RandomAccessFile(source, "r");RandomAccessFile dst = new RandomAccessFile(dest, "rw")) {src.seek(start);dst.seek(start);byte[] buffer = new byte[8192];int bytesRead;while (src.getFilePointer() < end && (bytesRead = src.read(buffer)) != -1) {dst.write(buffer, 0, bytesRead);}}});}executor.shutdown();executor.awaitTermination(1, TimeUnit.HOURS);
}

四、选型建议

  1. 文本处理:优先使用字符流(如BufferedReader
  2. 大文件传输:采用NIO的FileChannelFiles.copy()
  3. 高并发场景:必须使用NIO + 多线程方案
  4. 兼容性需求:旧系统可保留BIO实现

五、总结

Java IO体系经历了从BIO到NIO的演进,现代开发应优先采用NIO方案。通过合理选择字节流/字符流,结合NIO的零拷贝特性,可显著提升文件处理性能。实际开发中需根据文件类型、大小和并发需求综合选择技术方案。

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

相关文章:

  • postgresql安装教程-个人笔记
  • 股票分红派息及其数据获取(使用Python)
  • selenium爬取图书信息
  • 关于JVM
  • 低速信号设计之 RGMII 篇
  • Rk3568驱动开发_非阻塞IO_16
  • 有关Mysql数据库的总结
  • Pytest 输出捕获详解:掌握如何查看和控制打印信息
  • Nacos 探活机制深度解析:临时 / 永久实例差异及与 Sentinel 的熔断协作
  • C++11之右值引用与移动语义(提高效率)重要
  • 「日拱一码」033 机器学习——严格划分
  • 【VASP】VASP 机器学习力场(MLFF)实战
  • 机器学习对词法分析、句法分析、浅层语义分析的积极影响
  • Taro 本地存储 API 详解与实用指南
  • 京东疯狂投资具身智能:众擎机器人+千寻智能+逐际动力 | AI早报
  • 从“被动照料”到“主动预防”:智慧养老定义的养老4.0时代
  • 迁移科技3D视觉系统:赋能机器人上下料,开启智能制造高效新纪元
  • Nacos中feign.FeignException$BadGateway: [502 Bad Gateway]
  • 第15次:商品搜索
  • Laravel 系统版本查看及artisan管理员密码找回方法针对各个版本通用方法及原理-优雅草卓伊凡
  • Java-78 深入浅出 RPC Dubbo 负载均衡全解析:策略、配置与自定义实现实战
  • LeetCode - 3274. Check if Two Chessboard Squares Have the Same Color
  • 【Semi笔记】Semisupervised Change Detection With Feature-Prediction Alignment
  • .NET SDK 9.0.200引入对SLNX解决方案文件的支持
  • compser json和lock的作用区别
  • 【qml-3】qml与c++交互第二次尝试(类型方式)
  • 【C++11】哈希表与无序容器:从概念到应用
  • ElasticSearch:不停机更新索引类型(未验证)
  • git switch
  • (LeetCode 面试经典 150 题) 219. 存在重复元素 II (哈希表)