以写文件速度进行比较。分别比较传统IO流、缓冲流、和NIO的速度。均写80000k的数据。本次测试环境是jdk8
一、传统IO
long l1 = System.currentTimeMillis();
byte[] b = new byte[]{1,2,3,4,5,6,7,8};
FileOutputStream fos = null;
try {
fos = new FileOutputStream("test.txt");
for(int i=0;i<10240000;i++){
fos.write(b);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(fos !=null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
long l2 = System.currentTimeMillis();
System.out.println("FileOutputStream use time:" + (l2-l1));
}
运行5次的结果:
FileOutputStream use time:37292
FileOutputStream use time:37588
FileOutputStream use time:36913
FileOutputStream use time:37772
FileOutputStream use time:37772
二、缓冲流
long l1 = System.currentTimeMillis();
byte[] b = new byte[]{1,2,3,4,5,6,7,8};
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream("test1.txt"), 10240);
for(int i=0;i<10240000;i++){
bos.write(b);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(bos != null){
try {
bos.flush();
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
long l2 = System.currentTimeMillis();
System.out.println("BufferedOutputStream use time:"+(l2-l1));
}
运行5次结果:
BufferedOutputStream use time:345
BufferedOutputStream use time:342
BufferedOutputStream use time:490
BufferedOutputStream use time:344
BufferedOutputStream use time:341
三、NIO
long l1 = System.currentTimeMillis();
byte[] b = new byte[]{1,2,3,4,5,6,7,8};
ByteBuffer bb = ByteBuffer.allocate(10240);
FileOutputStream fos = null;
FileChannel fc = null;
try {
fos = new FileOutputStream("test2.txt");
fc = fos.getChannel();
bb.clear();
for(int i=0;i<8000;i++){
bb.clear();
int p = bb.position();
int c = bb.capacity();
while(p + b.length <= c){
bb.put(b);
p = bb.position();
}
bb.flip();
fc.write(bb);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
if(fos != null){
fos.close();
}
if(fc != null){
fc.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long l2 = System.currentTimeMillis();
System.out.println("NIO use time:"+(l2-l1));
}
运行5次结果:
NIO use time:207
NIO use time:215
NIO use time:204
NIO use time:212
NIO use time:200
从以上运行结果来看,传统的IO的写文件速度明显要低于缓冲流及NIO,缓冲流与NIO相差不大,NIO稍微快些。从jdk1.4以后出现了NIO,传统的IO流是按字节读写数据,NIO是按块读写数据,NIO将耗时最大的IO操作交给底层的操作系统来完成,这大大优化了IO速度。jdk1.4以后的java.io包的一些类的设计也是基于NIO的思想,提供按块读写数据。