最近因为准备好好学学Netty,在看nio的东西,据说NIO比io的效率快很多,决定写个小程序试试,下面是代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import org.apache.log4j.Logger;
public class Test {
private static final Logger logger = Logger.getLogger(Test.class);
public static void main(String[] args) throws IOException{
int count=1000;
long begin = System.currentTimeMillis();
for(int i=0;i<=count;i++){
ioCopy();
}
long end = System.currentTimeMillis();
logger.info("ioCopy()耗时:"+(end-begin)+"毫秒.");
long begin1 = System.currentTimeMillis();
for(int i=0;i<=count;i++){
nioCopy();
}
long end1 = System.currentTimeMillis();
logger.info("nioCopy()耗时:"+(end1-begin1)+"毫秒.");
}
/**
* 传统流式io的方式cofy文件
* @throws IOException
*/
public static void ioCopy() throws IOException{
File f = new File("E:\\OnKeyDetector.log");
File fout = new File("E:\\111.txt");
if(!f.exists()){
logger.info("要读取的文件不存在");
}else{
if(!fout.exists()){
fout.createNewFile();
}
FileInputStream fis = new FileInputStream(f);
FileOutputStream fos = new FileOutputStream(fout,true);
int temp = 0;
while( (temp=fis.read()) != -1){
fos.write(temp);
}
fout.delete();
}
}
/**
* nio的方式cofy文件
* @throws IOException
*/
public static void nioCopy() throws IOException{
File f = new File("E:\\OnKeyDetector.log");
File fout = new File("E:\\111.txt");
if(!f.exists()){
logger.info("要读取的文件不存在");
}else{
if(!fout.exists()){
fout.createNewFile();
}
FileInputStream fis = new FileInputStream(f);
FileChannel fc = fis.getChannel();
ByteBuffer bf = ByteBuffer.allocate(1024);
FileOutputStream fos = new FileOutputStream(fout,true);
FileChannel fcout = fos.getChannel();
while(fc.read(bf) != -1){
bf.flip();
fcout.write(bf);
bf.clear();
}
fout.delete();
}
}
}
运行结果如下:
2017-04-12 17:17:53 com.creditease.rgs.test.Test.main(Test.java:21) - [INFO] ioCopy()耗时:179872毫秒.
2017-04-12 17:17:54 com.creditease.rgs.test.Test.main(Test.java:28) - [INFO] nioCopy()耗时:1101毫秒.
由结果看,确实不是一个量级,当然,这里的程序只是很粗糙的对效率做个大概的对比,如果要做到严谨程序还得好好改改,不过由此可以看出NIO和阻塞io的效率差别真的很大,这样就可以放心的去好好学学NIO以及Netty啦。
NIO知识入门可参考:
https://www.ibm.com/developerworks/cn/education/java/j-nio/j-nio.html