本站首页    管理页面    写新日志    退出


«September 2025»
123456
78910111213
14151617181920
21222324252627
282930


公告

戒除浮躁,读好书,交益友


我的分类(专题)

日志更新

最新评论

留言板

链接

Blog信息
blog名称:邢红瑞的blog
日志总数:523
评论数量:1142
留言数量:0
访问次数:9704996
建立时间:2004年12月20日




[java语言]java的nio真的比io快吗
原创空间,  软件技术,  电脑与网络

邢红瑞 发表于 2005/6/6 16:19:33

dk1.4推出了java nio,加入了很多新的特性,sun也说nio的性能优于io,但是我使用中发现并非如此.io的copyfile代码public static void copyFile(File source, File dest) throws IOException {        if(!dest.exists()) {            dest.createNewFile();        }        InputStream in = null;        OutputStream out = null;        try {            in = new FileInputStream(source);            out = new FileOutputStream(dest);                        // Transfer bytes from in to out            byte[] buf = new byte[1024];            int len;            while ((len = in.read(buf)) > 0) {                out.write(buf, 0, len);            }        } finally {            if(in != null) {                in.close();            }            if(out != null) {                out.close();            }        }    }nio代码public static void copyFile2(File sourceFile, File destFile) throws IOException {        if(!destFile.exists()) {            destFile.createNewFile();        }                FileChannel source = null;        FileChannel destination = null;        try {            source = new FileInputStream(sourceFile).getChannel();            destination = new FileOutputStream(destFile).getChannel();            destination.transferFrom(source, 0, source.size());        } finally {            if(source != null) {                source.close();            }            if(destination != null) {                destination.close();            }        }            }这里没用使用,byte[] buf = new byte[1024];  int len;  while ((len = in.read(buf)) > 0) {   out.write(buf, 0, len);  }而是使用transferFrom,因为它是本地方法,优化过的.还可以使用 MappedByteBuffer public static void copyFileNio(File source, File dest) throws IOException                {                FileInputStream fi = new FileInputStream(source);                FileChannel fic = fi.getChannel();                MappedByteBuffer mbuf = fic.map(                                FileChannel.MapMode.READ_ONLY, 0, source.length());                fic.close();                fi.close();                        FileOutputStream fo = new FileOutputStream(dest);                FileChannel foc = fo.getChannel();                foc.write(mbuf);                foc.close();                fo.close();            }当时做的测试时,在linux下,对于小而文件,nio的速度远远高于io,大文件nio的性能要高于io.但是在win2k下,使用MappedByteBuffer的效率很低,比直接读流慢,大文件nio的性能不是很高.


阅读全文(4445) | 回复(0) | 编辑 | 精华
 



发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.047 second(s), page refreshed 144761804 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号