闲来无事,看到nio相关文章,于是想测试下nio和io的性能对比,不多说了,看下代码,大家一起讨论下,我觉得nio不是在性能方面对io的提升,而是其他方面的补充,比如阻塞和非阻塞io,不过这些概念理解比较差,还望赐教。
package com.nio;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class CopyFile {
public static void main(String[] args) throws Exception {
Long startTime = System.currentTimeMillis();
readWriteByIo();
// readWriteFileByNio();
Long endTime = System.currentTimeMillis();
System.out.println("用时:" + (endTime - startTime));
}
public static void readWriteFileByNio() throws Exception {
// String inFile = "d:/root.txt";
// String outFile = "d:/target.txt";
String inFile = "d:/my documents/view.log";
String outFile = "d:/view.log";
// 获取源文件和目标文件的输入输出流
FileInputStream fin = new FileInputStream(inFile);
FileOutputStream fout = new FileOutputStream(outFile);
// 获取输入输出通道
FileChannel fcin = fin.getChannel();
FileChannel fcout = fout.getChannel();
// 创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
// clear方法重设缓冲区,使它可以接受读入的数据
buffer.clear();
// 从输入通道中将数据读到缓冲区
int r = fcin.read(buffer);
// read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
if (r == -1) {
break;
}
// flip方法让缓冲区可以将新读入的数据写入另一个通道
buffer.flip();
// 从输出通道中将数据写入缓冲区
fcout.write(buffer);
}
}
public static void readWriteByIo() throws FileNotFoundException {
// String inFile = "d:/root.txt";
// String outFile = "d:/target.txt";
String inFile = "d:/my documents/view.log";
String outFile = "d:/view.log";
// 获取源文件和目标文件的输入输出流
FileInputStream fin = new FileInputStream(inFile);
FileOutputStream fout = new FileOutputStream(outFile);
InputStreamReader isr = null;
OutputStreamWriter osw = null;
BufferedReader br = null;
BufferedWriter bw = null;
try {
String line = null;
isr = new InputStreamReader(fin, "utf-8");
br = new BufferedReader(isr);
osw = new OutputStreamWriter(fout, "utf-8");
bw = new BufferedWriter(osw);
while((line = br.readLine()) != null){
bw.write(line + "\n");
}
bw.flush();
fin.close();
fout.close();
isr.close();
osw.close();
br.close();
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试结果:
使用java nio与java io读写文件性能对比
测试1:文件大小174M
nio用时:
第一次测试:用时:2906ms
第二次测试:用时:3219ms
第三次测试:用时:2844ms
io用时:
第一次测试:用时:2718ms
第二次测试:用时:2047ms
第三次测试:用时:1984ms
测试2:文件大小3.09G
nio用时:
第一次测试:用时:228204ms
第二次测试:用时:231547ms
第三次测试:用时:249828ms
io用时:
第一次测试:用时:204594ms
第二次测试:用时:237672ms
第三次测试:用时:249672ms