疯狂

STANDING ON THE SHOULDERS OF GIANTS
posts - 481, comments - 486, trackbacks - 0, articles - 1
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

nio和io读写文件

Posted on 2010-02-05 15:49 疯狂 阅读(806) 评论(0)  编辑  收藏 所属分类: java


nio:
public static void testNio() throws IOException{
 long start = System.currentTimeMillis();
 FileInputStream in = new FileInputStream(new File("C:\\y.war"));
 FileOutputStream out = new FileOutputStream(new File("C:\\copy1.war"));
 FileChannel outc = out.getChannel();
 FileChannel inc = in.getChannel();
 ByteBuffer inb = ByteBuffer.allocate(1024*1024);//1m
 int i = 0;
 while(true){
  i++;
  System.out.println("第"+i+"次传输...");
  if(inb.position()>0){
   System.out.println("clear...");
   inb.clear();
  }
  if(inc.read(inb)==-1)break;
  inb.flip();
  outc.write(inb);
 }
 inc.close();
 outc.close();
 System.out.println("耗时:"+(System.currentTimeMillis()-start)+"毫秒");
}

io:
public static void testIo() throws IOException{
 long start = System.currentTimeMillis();
 FileInputStream in = new FileInputStream(new File("C:\\y.war"));
 FileOutputStream out = new FileOutputStream(new File("C:\\copy2.war"));
 
 BufferedInputStream inc = new BufferedInputStream(in);
 BufferedOutputStream outc = new BufferedOutputStream(out);
 byte[] inb = new byte[1024*1024];//1m
 int i = 0;
 int l=-1;
 while(true){
  i++;
  System.out.println("第"+i+"次传输...");
  if((l=inc.read(inb))==-1)break;
  outc.write(inb,0,l);
 }
 inc.close();
 outc.flush();
 outc.close();
 System.out.println("耗时:"+(System.currentTimeMillis()-start)+"毫秒");
}
}
同样的16.4 MB的文件100次读写测试平均耗时:nio耗时:80毫秒 io耗时:105毫秒

只有注册用户登录后才能发表评论。


网站导航: