Java NIO和BIO读写简单比较


通过对文件的读写所花的时间来进行比较。

一、读写的文件

二、实例代码

package nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOVSIO
{
	public static void readIO() throws Exception{
		File file = new File("E:/迅雷下载/美人鱼.HD.720p.国语中字.rmvb");
		File file2 = new File("E:/迅雷下载/美人鱼.HD.720p.国语中字io.rmvb");
		FileInputStream fis = new FileInputStream(file);
		FileOutputStream fos = new FileOutputStream(file2);
		byte[] buffer = new byte[1024];
		int len = -1;
		while((len = fis.read(buffer))!= -1){
			fos.write(buffer, 0, len);
		}
		fis.close();
		fos.close();
	}
	public static void readNIO() throws Exception{
		File file = new File("E:/迅雷下载/美人鱼.HD.720p.国语中字.rmvb");
		File file3 = new File("E:/迅雷下载/美人鱼.HD.720p.国语中字nio.rmvb");
		FileInputStream fis = new FileInputStream(file);
		FileOutputStream fos = new FileOutputStream(file3);
		FileChannel channel = fis.getChannel();
		FileChannel outchannel = fos.getChannel();
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while(channel.read(buffer)!=-1){
			buffer.flip();
		    outchannel.write(buffer);
			buffer.clear();
		}
		channel.close(); 
		fis.close();
		fos.close();
	}
	public static void main(String[] args) throws Exception
	{
		
		long nioStart = System.currentTimeMillis();
		readNIO();
		System.out.println("nio-time: "+((System.currentTimeMillis()-nioStart)));
		long ioStart = System.currentTimeMillis();
		readIO();
		System.out.println("io-time: "+((System.currentTimeMillis()-ioStart)));
	}
}

三次测试的结果:

           

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值