操作文件的两种方式Channel or Input/OutPstream

下面介绍两种读写文件的对比, 

1:InputStream/OutputStream操作byte[]  

2:Channel操作buffer

(Reader /Writer读写文件的方式就不比较了,其性能比上面两种方式差很多)

先来说说两种方式对比后的结果:总体来说第一种方式对比第二种方式有如下的缺点

1:速度慢,下面代码运行结果表明 Channel操作buffer速度快于InputStream/OutputStream操作byte[]

下面是我的测试代码:从F盘中读取spittr.war文件,然后重命名写入F盘。输出所需要的时间。

 

public class Test {
	public static void main(String[] args) throws IOException{
		byStream();//InputStream/OutputStream操作byte[]
		byChannel(); //Channel操作buffer
	}
	
	static void byChannel()  throws IOException {
		File file = new File("F:"+File.separator+"spittr.war");
		FileInputStream fins = new FileInputStream(file);
		FileChannel fc = fins.getChannel();

		File file2 = new File("F:"+File.separator+"Channel.war");
		FileOutputStream fos = new FileOutputStream(file2);
		FileChannel foc = fos.getChannel();

		ByteBuffer buffer = ByteBuffer.allocate(1024*1024);
		int temp = 0;
		
		long start = System.currentTimeMillis();
		
		while ((temp = fc.read(buffer) )!=-1) {
			buffer.flip();
			foc.write(buffer);
			buffer.clear();
		}

		System.out.println("byChannel:"+(System.currentTimeMillis() - start));
		fc.close();
		fins.close();
		foc.close();
		fos.close();
	}
	
	static void byStream() throws IOException{
		
		File file = new File("F:"+File.separator+"spittr.war");
		FileInputStream fins = new FileInputStream(file);

		File file2 = new File("F:"+File.separator+"stream.war");
		FileOutputStream fos = new FileOutputStream(file2);

		int temp = 0;
		
		long start = System.currentTimeMillis();
		
		byte[] buffer = new byte[1024*1024];
		while ((temp = fins.read(buffer) )!=-1) {
			fos.write(buffer,0,temp);
		}

		System.out.println("byStream:"+(System.currentTimeMillis() - start));
		fins.close();
		fos.close();
	}
}

输出结果:

第一次运行:
byStream:40
byChannel:30

第二次运行:

byStream:46
byChannel:27

第三次运行:

byStream:44
byChannel:28

上面的输出结果印证了第二条结果。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值