NIO和阻塞io的读写文件效率差异

最近因为准备好好学学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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值