Java API實現檔案複製
阿新 • • 發佈:2019-01-07
public class FileUtil {
/** * 利用緩衝流複製檔案 * @param from原始檔 * @param to目標檔案 */ public static boolean bufCopy(String from,String to) { //InputStream是所有出輸入流的父類 InputStream in = null; //OutputStream是所有輸出流的父類 OutputStream out = null; try { in = new BufferedInputStream( new FileInputStream(from)); out = new BufferedOutputStream( new FileOutputStream(to)); //讀取資料的int型別,第八位有效,若為-1則表示檔案讀取結束 int temp; while ((temp = in.read()) != -1) { //不直接寫檔案,將資料寫入緩衝陣列中 //在流關閉、緩衝陣列飽和,會寫入檔案並清理緩衝陣列 out.write(temp); } System.out.println("OK"); return true; } catch (FileNotFoundException e1) { String msg = e1.getMessage(); System.out.println(msg+":檔案不存在!"); return false; } catch (IOException e2) { System.out.println("檔案讀寫錯誤:"+e2); return false; } finally { if (in != null ) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null ) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 利用緩衝區複製檔案 * @param src原始檔 * @param dst目標檔案 * @throws CopyException自定義讀寫異常 */ public static void Copy(String src,String dst) throws CopyException{ FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dst); //定義緩衝區,臨時存放讀取資料 byte[] data = new byte[8*1024]; //返回有效資料長度 int temp; while ((temp = in.read(data)) != -1) { //按有效長度,將臨時陣列資料寫入檔案中 out.write(data,0,temp); } System.out.println("OK"); } catch (FileNotFoundException e1) { throw new CopyException("檔案不存在!",e1); } catch (IOException e2) { throw new CopyException("檔案讀寫錯誤!",e2); } finally { if (in != null ) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null ) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
}
/**
* 自定義讀寫異常
* @author Administrator
*
*/
class CopyException extends Exception{
public CopyException() { super(); // TODO Auto-generated constructor stub } public CopyException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public CopyException(String message) { super(message); // TODO Auto-generated constructor stub } public CopyException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub }
}
檔案讀取方案:
*方案一、直接使用FileInputStream,逐個位元組讀寫(效率最低);
方案二、自定義byte陣列,作為臨時資料儲存區域,批量讀寫資料;
方案三、利用緩衝流(過濾流)管理緩衝區,每次還是讀取一個byte。*
緩衝流:在其他流的基礎上拓展功能,擴充緩衝區,提高工作效率。