端午之际,撸了两把,然后学习学习nio的知识。今天闲暇比较了一下 通过 nio 和 io 进行文件复制时的速度比较:
前两天项目出现了bug,所以让客户那边的同事传来了tomcat log, 文件是100多M, 还是比较大的,顿时想起了大数据是多么牛逼的技术。 刚好我可以用此文件来测试一下 nio 和 io 的运行效率。
上代码吧:
package myNewIO;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
public class TrabsferTromAndTo {
public static void transfer() throws IOException{
RandomAccessFile raf = new RandomAccessFile("D:\\Users\\pyt\\tmp\\log.txt","r");
RandomAccessFile toFile = new RandomAccessFile("D:\\Users\\pyt\\tmp\\log_st.txt","rw");
FileChannel fromChannel = raf.getChannel();
FileChannel toChannel =toFile.getChannel();
long target = fromChannel.size();
System.out.println("file Size:"+target);
long startTime = System.currentTimeMillis();
fromChannel.transferTo(0, target, toChannel);
fromChannel.close();
toChannel.close();
raf.close();
toFile.close();
long finishTime = System.currentTimeMillis();
System.out.println("Channel Need time is:"+(finishTime - startTime));
}
public static void readByteByBuffer() throws IOException{
FileInputStream in = new FileInputStream("D:\\Users\\pyt\\tmp\\log.txt");
FileOutputStream out = new FileOutputStream("D:\\Users\\pyt\\tmp\\log-BUFFER.txt");
BufferedInputStream bufIn = new BufferedInputStream(in);
BufferedOutputStream bufOut = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
long startTime = System.currentTimeMillis();
int len = bufIn.read(buff);
while(len != -1){
bufOut.write(buff, 0, len);
len = bufIn.read(buff);
}
in.close();
bufOut.close();
long finishTime = System.currentTimeMillis();
System.out.println("Buffer Need time is:"+(finishTime-startTime));
}
public static void readByteByStream() throws IOException{
FileInputStream in = new FileInputStream("D:\\Users\\pyt\\tmp\\log.txt");
FileOutputStream out = new FileOutputStream("D:\\Users\\pyt\\tmp\\log-TREAM.txt");
byte[] buff = new byte[2048];
long startTime = System.currentTimeMillis();
int len = in.read(buff);
while(len != -1){
out.write(buff, 0, len);
len = in.read(buff);
}
in.close();
out.close();
long finishTime = System.currentTimeMillis();
System.out.println("Stream Need time is:"+(finishTime-startTime));
}
public static void main(String[]args) throws IOException{
transfer() ;
readByteByBuffer();
readByteByStream();
}
}
第一次运行打印结果是:
file Size:172750600
Channel Need time is:197
Buffer Need time is:367
Stream Need time is:570
第二次:
第二次:
file Size:172750600
Channel Need time is:194
Buffer Need time is:375
Stream Need time is:563
可以看出通过 nio 库复制此文件比通过 io 库复制此文件的速度高将近一倍,当然高出一倍只是相对我这个文件的。
本文通过对比NIO和IO两种方式复制100多MB大小文件的速度,展示了NIO在文件复制任务上的显著优势。实测结果显示,使用NIO进行文件复制的速度比传统IO快近一倍。

2047

被折叠的 条评论
为什么被折叠?



