NIO的学习

参考 http://wenku.baidu.com/link?url=rq-BEp3Et4JRrE62f2Lv9hq8nT_Gq0XPb65h8OBqTAt-ILfqKmdjIhVEp8bctIdm0uqWJG6P_U0-B8gYSjSEUGgmEwmiQIKobcGxvBM3YsG

nio是非阻塞io,nio 可以理解为new io,也可以理解为net+io,所以,我们探讨一下非阻塞io的过程。

1.channel是通道,是对原来的流的模拟,可以实现同时读写,双向性。而流呢,我们知道inputstream outputstream 只能进行单项读写。

2,缓冲区,其实就是数组,byte数组,int数组,等类型,以往是阻塞的,流的处理,此处引入缓冲区,无论读写文件,网络流,都要从缓冲区读写。

 1 import java.io.File;
 2 import java.io.FileInputStream;
 3 import java.io.FileNotFoundException;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.nio.ByteBuffer;
 7 import java.nio.channels.FileChannel;
 8 
 9 //这个例子是文件IO,中传统IO和NIO的例子
10 public class NIO学习 {
11     public static void ioRead(File f) throws IOException
12     {
13         FileInputStream  fin=new FileInputStream(f);
14         byte[] b=new byte[1024];
15         fin.read(b);
16         System.out.println(new String(b));
17         
18     }
19     public static void nioRead(File f) throws IOException
20     {
21         
22         FileInputStream fin=new FileInputStream(f);
23         FileChannel  channal=fin.getChannel();
24         ByteBuffer by=ByteBuffer.allocate(1024);
25         channal.read(by);
26         byte n[]=by.array();
27         System.out.println(new String(n));
28         
29         
30         
31     }
32     public static void copyFile(File f1,File f2) throws IOException
33     {
34         //获得源文件的输入流
35         FileInputStream input=new FileInputStream(f1);
36         //获得文件的输入流
37         FileOutputStream output=new FileOutputStream(f2);
38         
39         //获得channel
40         FileChannel cinput=input.getChannel();
41         FileChannel coutput=output.getChannel();
42         
43         //缓存的设置
44         ByteBuffer by=ByteBuffer.allocate(1024);
45         
46         while(true)
47         {
48             by.clear(); //postion=0,limit=capacity
49             int r=cinput.read(by);
50             if(r==-1) break;
51             by.flip();
52             coutput.write(by);
53             
54             
55             
56         }
57         
58         
59         
60         
61         
62         
63         
64         
65         
66     }
67 
68     /**
69      * @param args
70      * @throws IOException 
71      */
72     public static void main(String[] args) throws IOException {
73         // TODO Auto-generated method stub
74         File f1=new File("E:\test\source.txt");
75         File f2=new File("E:\test\dest.txt");
76         copyFile(f1,f2);
77       //  ioRead(f1);
78         nioRead(f2);
79     }
80 
81 }
原文地址:https://www.cnblogs.com/hansongjiang/p/3885153.html