Posted on 2010-02-05 15:49
疯狂 阅读(805)
评论(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毫秒