java nio 的一个简单例子:拷贝文件
? ? ?下面是java中的nio一个例子,拷贝文件?
通过这个例子和注释相信能让你很容易的理解nio的使用
?
public static void copy()throws Exception{String source="e:/a.wmv";String dest="e:/b.wmv";FileInputStream inputStream=new FileInputStream(source);FileOutputStream outputStream=new FileOutputStream(dest);FileChannel iChannel=inputStream.getChannel();FileChannel oChannel=outputStream.getChannel();ByteBuffer buffer=ByteBuffer.allocate(1024);long l1=System.currentTimeMillis();while(true){buffer.clear();//pos=0,limit=capcity,作用是让ichannel从pos开始放数据int r=iChannel.read(buffer);if(r==-1)//到达文件末尾break;buffer.limit(buffer.position());//buffer.position(0);//这两步相当于 buffer.flip();oChannel.write(buffer);//它们的作用是让ochanel写入pos - limit之间的数据 }inputStream.close();outputStream.close();System.out.println("complete:"+(System.currentTimeMillis()-l1));}?
?
ps:
关于buffer,有以下特点
1、buffer相当于一个功能强大的数组
2、buffer有几个特别的变量 pos(位置),mark(标记),limits(限制),capacity(容量),他们的关系如下
? ? ?0 <= 标记 <= 位置 <= 限制 <= 容量?
3、对应buffer的读写,须注意以下几点
3-1、读操作是从pos开始,到limits,读操作发生后,pos会递增,至于递增多少,则看具体情况
3-2、写操作类似,从pos开始写,最多能写到limits处,写操作发生后,pos会递增,递增多少看写的数据如何
?
?
?
?
?
1 楼 bingyingao 2011-11-18 没接触过nio,不过上次找工作面试时被问过,学习了...