读书人

java IO跟NIO测试

发布时间: 2012-11-10 10:48:50 作者: rapoo

java IO和NIO测试

测试环境:cpu:Q9500 4核 ? ?频率2.83GHZ ? ? ?内存4G ? 文件大小200M

?

测试代码

?

package com.lottery;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class CopyFile {public static void main(String[] args) throws Exception {readWriteFileByNio();readWriteFileByNioTransferTo();readWriteByIo();}public static void readWriteFileByNio() throws Exception {Long startTime = System.currentTimeMillis();String inFile = "D:/lottery.log4j";String outFile = "d:/test/1";FileChannel fcin = new FileInputStream(inFile).getChannel();FileChannel fcout = new FileOutputStream(outFile).getChannel();ByteBuffer buffer = ByteBuffer.allocate(1024);while (true) {buffer.clear();int r = fcin.read(buffer);if (r == -1) {break;}buffer.flip();fcout.write(buffer);}fcin.close();fcout.close();Long endTime = System.currentTimeMillis();System.out.println("readWriteFileByNio:" + (endTime - startTime));}public static void readWriteFileByNioTransferTo() throws Exception {Long startTime = System.currentTimeMillis();String inFile = "D:/lottery.log4j";String outFile = "d:/test/2";FileChannel fcin = new FileInputStream(inFile).getChannel();FileChannel fcout = new FileOutputStream(outFile).getChannel();fcin.transferTo(0, fcin.size(), fcout);fcin.close();fcout.close();Long endTime = System.currentTimeMillis();System.out.println("readWriteFileByNioTransferTo:" + (endTime - startTime));}public static void readWriteByIo() throws FileNotFoundException {Long startTime = System.currentTimeMillis();String inFile = "D:/lottery.log4j";String outFile = "d:/test/3";BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(outFile));BufferedInputStream is = new BufferedInputStream(new FileInputStream(inFile));byte[] buffer = new byte[1024];try {while (is.read(buffer) != -1) {os.write(buffer);}os.close();is.close();} catch (Exception e) {e.printStackTrace();}Long endTime = System.currentTimeMillis();System.out.println("readWriteByIo:" + (endTime - startTime));}}

?

测试结果:

readWriteFileByNio:3453

readWriteFileByNioTransferTo:1323

readWriteByIo:791

?

结论:此测试数据还是不是很充分,没有通过多个文件大小比较。但是单单从这一个测试结果来看使用Buffer的IO性能要大大好于NIO,不使用Buffer的IO和NIO性能差距不大

其实以我看来NIO文件操作的优势不再于全文件的读写,而在于可以随意访问文件块

另外NIO在网络上面提供了非阻塞读写。

读书人网 >编程

热点推荐