IO流:
public static void fileCopy(String source,String target) throws IOException {
Long beginTime = System.nanoTime();
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(source);
out = new FileOutputStream(target);
int total;
byte[] buff = new byte[1024];
while ((total = in.read(buff)) != -1) {
out.write(buff, 0, total);
}
}finally {
in.close();
out.close();
Long endTime = System.nanoTime();
System.out.println(" IO时长:"+(endTime-beginTime)+"纳秒");
}
}
NIO
public static void fileCopyNio(String source ,String target) throws IOException {
Long beginTime = System.nanoTime();
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
inChannel = new FileInputStream(source).getChannel();
outChannel = new FileOutputStream(target).getChannel();
ByteBuffer buff = ByteBuffer.allocate(1024);
while(inChannel.read(buff) != -1){
buff.flip();
outChannel.write(buff);
buff.clear();
}
//这个也可以
// outChannel.transferFrom(inChannel, 0 , inChannel.size());
}finally {
inChannel.close();
outChannel.close();
Long endTime = System.nanoTime();
System.out.println("NIO时长:"+(endTime - beginTime)+"纳秒");
}
}
发现小文件测试的时候io速度更快...而大文件是nio更快