参考 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数组,等类型,以往是阻塞的,流的处理,此处引入缓冲区,无论读写文件,网络流,都要从缓冲区读写。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel; //这个例子是文件IO,中传统IO和NIO的例子
public class NIO学习 {
public static void ioRead(File f) throws IOException
{
FileInputStream fin=new FileInputStream(f);
byte[] b=new byte[1024];
fin.read(b);
System.out.println(new String(b)); }
public static void nioRead(File f) throws IOException
{ FileInputStream fin=new FileInputStream(f);
FileChannel channal=fin.getChannel();
ByteBuffer by=ByteBuffer.allocate(1024);
channal.read(by);
byte n[]=by.array();
System.out.println(new String(n)); }
public static void copyFile(File f1,File f2) throws IOException
{
//获得源文件的输入流
FileInputStream input=new FileInputStream(f1);
//获得文件的输入流
FileOutputStream output=new FileOutputStream(f2); //获得channel
FileChannel cinput=input.getChannel();
FileChannel coutput=output.getChannel(); //缓存的设置
ByteBuffer by=ByteBuffer.allocate(1024); while(true)
{
by.clear(); //postion=0,limit=capacity
int r=cinput.read(by);
if(r==-1) break;
by.flip();
coutput.write(by); } } /**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File f1=new File("E:\\test\\source.txt");
File f2=new File("E:\\test\\dest.txt");
copyFile(f1,f2);
// ioRead(f1);
nioRead(f2);
} }