NIO

NIO
------------
 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)
  
  读写
  
 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 }
NIO拷贝文件

 


  
posted @ 2018-07-02 11:46  star521  阅读(122)  评论(0编辑  收藏  举报