NIO
NIO
------------
new IO
非阻塞
1.FileInputStream
2.FileOutputStream
------------
new IO
非阻塞
1.FileInputStream
2.FileOutputStream
Buffer
----------------
ByteBuffer
相关概念
capacity //容量,数组的长度
limit //限制,可以使用的空间大小
position //位置,指针,开始操作缓冲区的索引
mark //记号,可以通过reset方法将指针重置到mark的位置
0<= mark <= position <= limit <= capacity
flip() //拍板,limit = position, position = 0 确定有效数据,放开有效的部分
clear() //position = 0; limit = capacity 整个缓冲区放开
Channel
--------------------
通道 创建就开启
到硬件设备、文件、Socket、或网路组件的打开的链接,这些组件可以执行IO操作
isOpen 判断通道打开状态
FileChannel + ByteBuffer完成文件的读写
FileInputStream -> FileChannel 读
FileOutputStream -> FileChannel 写
文件拷贝
输入流
源文件通道、
getChannel
输出流
输出文件通道
分配字节缓冲区
ByteBuffer.allocate(1024)
读写
NIO拷贝文件
----------------
ByteBuffer
相关概念
capacity //容量,数组的长度
limit //限制,可以使用的空间大小
position //位置,指针,开始操作缓冲区的索引
mark //记号,可以通过reset方法将指针重置到mark的位置
0<= mark <= position <= limit <= capacity
flip() //拍板,limit = position, position = 0 确定有效数据,放开有效的部分
clear() //position = 0; limit = capacity 整个缓冲区放开
Channel
--------------------
通道 创建就开启
到硬件设备、文件、Socket、或网路组件的打开的链接,这些组件可以执行IO操作
isOpen 判断通道打开状态
FileChannel + ByteBuffer完成文件的读写
FileInputStream -> FileChannel 读
FileOutputStream -> FileChannel 写
文件拷贝
输入流
源文件通道、
getChannel
输出流
输出文件通道
分配字节缓冲区
ByteBuffer.allocate(1024)
读写

1 public class NioDemo { 2 public static void main(String[] args) throws Exception { 3 //输入流 4 FileInputStream fis = new FileInputStream("G:\\demo\\a.txt"); 5 //获取源文件通道 6 FileChannel srcfc = fis.getChannel(); 7 //输出流 8 FileOutputStream fos = new FileOutputStream("G:\\demo\\1000.txt"); 9 //获取目标通道 10 FileChannel destfc = fos.getChannel(); 11 12 //定义缓冲区 13 ByteBuffer buf = ByteBuffer.allocate(4); 14 //读写 15 while(srcfc.read(buf)!=-1){ 16 buf.flip();//拍板 指针到开头,限制到有效数据尾部 17 destfc.write(buf);//写 18 buf.clear();//放开所以缓冲区 19 Thread.sleep(50); 20 21 } 22 23 } 24 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下