NIO即New I/O。它的一大特性就是采用块的方式进行读写,提高了读写的速度。这样看来NIO似乎完全可以取代IO了。
事实却并非如此,由于IO也进行了类似的改进,所以在实际应用中,当缓冲区较小时,IO的速度反比NIO快!
今天就做了如下测试:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
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;
public class TestNioFile {
public static void main(String[] args) throws IOException {
long startTime=0;
long endTime=0;
//缓冲区大小
int size1=1024;
int size2=10240;
startTime=System.currentTimeMillis();
FileChannel fcout=new FileOutputStream("NioDest").getChannel();
FileChannel fcin=new FileInputStream("Source").getChannel();
ByteBuffer buffer=ByteBuffer.allocate(size1);
while(fcin.read(buffer)!=-1){
buffer.flip();
fcout.write(buffer);
buffer.clear();
}
endTime=System.currentTimeMillis();
System.out.println("采用nio方式复制时间为:"+(endTime-startTime)+"毫秒");
startTime=System.currentTimeMillis();
DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream("Source")));
DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream("IoDest")));
byte[] buf=new byte[1024];
while(dis.read(buf)!=-1){
dos.write(buf);
}
dis.close();
dos.close();
endTime=System.currentTimeMillis();
System.out.println("采用io方式复制时间为:"+(endTime-startTime)+"毫秒");
}
}
当复制的文件很小时(43K),输出结果如下:
采用nio方式复制时间为:31毫秒
采用io方式复制时间为:0毫秒
(8M)
采用nio方式复制时间为:781毫秒
采用io方式复制时间为:140毫秒
(311M)
采用nio方式复制时间为:26078毫秒
采用io方式复制时间为:17188毫秒
===========================================================
这次我们将缓冲区设置为size2,继续进行测试。
(43K)
采用nio方式复制时间为:47毫秒
采用io方式复制时间为:15毫秒
(8M)
采用nio方式复制时间为:172毫秒
采用io方式复制时间为:156毫秒
(311M)
采用nio方式复制时间为:13203毫秒
采用io方式复制时间为:12532毫秒
由此可见,缓冲区的大小对NIO的读写速度影响很大,当缓冲区为1024时,只有当文件很大的时候NIO的的速度才会比IO快(但对于300多M的文件来说,NIO的耗时仍然是IO的1.5倍还多!)。