Java NIO文件复制以及与传统IO效率对比

来源:互联网 发布:淘宝海外旗舰店真假 编辑:程序博客网 时间:2024/05/22 01:40

1.demo

package com.ccy.IO;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import org.junit.Test;public class CopyFileByNIO {private static final String PATH = "c:/css.pdf";private static final String DESPATH = "c:/css01.pdf";@Testpublic void copyFile() throws Exception{long start = System.currentTimeMillis();FileInputStream fileInputStream = new FileInputStream(new File(PATH));FileOutputStream fileOutputStream = new FileOutputStream(new File(DESPATH));byte[] buff = new byte[1024];int len = 0;while((len = fileInputStream.read(buff))!=-1){fileOutputStream.write(buff,0,len);fileOutputStream.flush();}fileOutputStream.close();fileOutputStream.close();System.out.println("Java IO spending : " + (System.currentTimeMillis() - start));}@Testpublic void copyFileByNIO() throws Exception{long start = System.currentTimeMillis();FileInputStream inputStream = new FileInputStream(new File(PATH));FileChannel inChannel = inputStream.getChannel();FileOutputStream fileOutputStream = new FileOutputStream(new File(DESPATH));FileChannel outChannel = fileOutputStream.getChannel();ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);   while (true) {int eof = inChannel.read(byteBuffer);if (eof == -1)break;byteBuffer.flip();outChannel.write(byteBuffer);byteBuffer.clear();}inChannel.close();outChannel.close();System.out.println("Java NIO spending : " + (System.currentTimeMillis() - start));}}

2.结果

Java NIO spending : 2434Java IO spending : 2414
从以上结果可以看出,我们无需对文件操作特意使用NIO的api,究其原因是因为FileInputStream 的底层已经是FileChannel 了,所以我们不需要画足添蛇



更多精彩内容请继续关注我的博客:http://blog.csdn.net/caicongyang

记录与分享,你我共成长 -from caicongyang





0 0
原创粉丝点击