1. 程式人生 > >java io 複製檔案與 nio 複製檔案的效率問題

java io 複製檔案與 nio 複製檔案的效率問題

這是除錯程式目的是計算它們的速度;
package com.leejuen.copy;

import java.io.File;

public class test {
	public static void main(String[] args)
	{
		File s = new File("D:\\struts2幫助文件.rar");
		File t = new File("E:\\struts2幫助文件.rar");
		long start,end;
		
		
		start = System.currentTimeMillis();
		FileChannelCopy.ChannelCopy(s, t);
		end = System.currentTimeMillis();
		System.out.println(end-start);
		
		start = System.currentTimeMillis();
		Copy.copyBuf(s, t);
		end = System.currentTimeMillis();
		System.out.println(end-start);
	}
}
這是普通的buf複製過程,這裡要提醒的是buf是阻塞的複製後一定要關不close或flush緩衝區。要不然會有少部分資料留在緩衝區裡沒有複製
package com.leejuen.copy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction;

public class Copy {
	
	
	public static void copyBuf(File s,File t)
	{
		InputStream bis = null;
		OutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(s));
			bos = new BufferedOutputStream(new FileOutputStream(t));
			byte[] b = new byte[1024];
			int i = 0;
			while(bis.read(b)!=-1)
			{
				bos.write(b);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		finally
		{
			try {
				bos.close();
				bis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

這是用channel管道複製過程
package com.leejuen.copy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class FileChannelCopy {
	public static void ChannelCopy(File s,File t)
	{
		FileInputStream fi = null;
		FileOutputStream fo = null;
		FileChannel in = null;
		FileChannel out = null;
		try {
			fi = new FileInputStream(s);
			fo = new FileOutputStream(t);
			in = fi.getChannel();
			out = fo.getChannel();
			in.transferTo(0, in.size(), out);//連線兩個通道,並且從in通道讀取,然後寫入out通道
		} catch (Exception e) {
			// TODO: handle exception
			
		}
		finally{
			  try {

	                fi.close();

	                in.close();

	                fo.close();

	                out.close();

	            } catch (IOException e) {

	                e.printStackTrace();

	            }
		}
	}
}

實驗過程中當檔案大小在比較小的情況(這裡筆者沒有生成足夠多的檔案來測試。不過這個比較小應該是在50~100M大小以下)以下時buf儲存明顯佔優勢。之後當檔案使用100M的資料時FileChannel明顯佔優勢。之後FileChannel就一直優勢。所以選擇什麼方式複製要看複製的檔案大小。不能一定的說那種方法就是好