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

来源:互联网 发布:上海争游网络首页 编辑:程序博客网 时间:2024/06/03 09:39
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方法执行之时间:79IO方法执行之时间:25188
原创粉丝点击