NIO与IO复制相同文件的时间

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_38868875/article/details/78191286
package com.csl.test;

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.junit.Test;
/**
 * 
 * @author Cherry
 * @date 2017年10月10日
 *
 */
public class TestNio {

	@Test
	public void show() throws IOException {
		String in = "e:/深入浅出MySQL全文.pdf";
		String out = "e:/深入浅出MySQL全文cpoy.pdf";
		copyNIO(in,out);
		copyIO(in, out);
	}

	public static void copyNIO(String in, String out) throws IOException {
		FileInputStream fis = new FileInputStream(new File(in));
		FileOutputStream fos = new FileOutputStream(new File(out));

		FileChannel inChannel = fis.getChannel();
		FileChannel outChannel = fos.getChannel();

		ByteBuffer buf = ByteBuffer.allocate(1024);

		long start = System.currentTimeMillis();

		while (true) {
			int i = inChannel.read(buf);
			if (i == -1) {
				break;
			}
			
			buf.flip();

			outChannel.write(buf);

			buf.clear();
		}

		long end = System.currentTimeMillis();

		System.out.println("NIO方法执行之时间:" + (end - start));
		inChannel.close();
		outChannel.close();
		fis.close();
		fos.close();
	}

	public static void copyIO(String in, String out) throws IOException {
		FileInputStream fis = new FileInputStream(new File(in));
		FileOutputStream fos = new FileOutputStream(new File(out));

		int i = 0;
		
		long start = System.currentTimeMillis();
		
		while ((i = fis.read()) != -1) {
			fos.write(i);
		}

		long end = System.currentTimeMillis();

		System.out.println("IO方法执行之时间:" + (end - start));
		fis.close();
		fos.close();
	}
}

执行时间之对比结果

NIO方法执行之时间:79
IO方法执行之时间:25188

------------------------------------------------------------------访问IT资料站学习更多IT知识!

猜你喜欢

转载自blog.csdn.net/baidu_38868875/article/details/78191286
今日推荐