天天看點

JAVA 複制檔案

package com.test;

import java.io.*;

public class CopyFileTest{

//參數oldFile如:d:/old.txt,參數newFile如d:/new.txt

 public void copyFile(String oldFile,String newFile){

  try{

   int bytesum = 0;

   int byteread = 0;

   File oldfile = new File(oldFile);

   //判斷檔案是否存在,如果檔案存在則實作該檔案向新檔案的複制

   if(oldfile.exists()){

    //讀取原檔案

    InputStream ins = new FileInputStream(oldFile);

    //建立檔案輸出流,寫入檔案

    FileOutputStream outs = new FileOutputStream(newFile);

    //建立緩沖區,大小為500位元組

    byte[] buffer = new byte[500];

    //每次從檔案流中讀取500位元組資料,計算目前為止讀取的資料總數

    while((byteread = ins.read(buffer)) != -1){

     bytesum += byteread;

     System.out.println(bytesum);

     //把目前緩沖區中的資料寫入新檔案

     outs.write(buffer,0,byteread);

    }

    ins.close();

   }

   else  //如果原檔案不存在,則扔出異常

    throw new Exception();

  }catch(Exception ex){

   System.out.print("原檔案不存在!");

   ex.printStackTrace();

  }

 }

 public static void main(String[] args){

  //建立類對象執行個體,并調用copyFile()函數,函數參數在執行程式時刻在控制台輸入

  //第一個參數表示老檔案,第二個參數表示新檔案

  CopyFileTest copyfile = new CopyFileTest();

  copyfile.copyFile("d:\\323324234.jpg", "E:\\20130307.jpg");

 }

}