文件的拷貝

import java.io.* ;
public class Copy{
   public static void main(String args[]){
     if(args.length!=2){     // 判斷是不是兩個參數
      System.out.println( "輸入的參數不正確。") ;
      System.out.println( "例:java Copy 源文件路徑 目標文件路徑") ;
      System.exit(1) ;   // 系統退出
    }
    File f1 = new File(args[0]) ;   // 源文件的File對象
    File f2 = new File(args[1]) ;   // 目標文件的File對象
     if(!f1.exists()){
      System.out.println( "源文件不存在!") ;
      System.exit(1) ;
    }
    InputStream input = null ;     // 準備好輸入流對象,讀取源文件
    OutputStream out = null ;     // 準備好輸出流對象,寫入目標文件
     try{
      input = new FileInputStream(f1) ;
    } catch(FileNotFoundException e){
      e.printStackTrace() ;
    }
     try{
      out = new FileOutputStream(f2) ;
    } catch(FileNotFoundException e){
      e.printStackTrace() ;
    }
     if(input!= null && out!= null){   // 判斷輸入或輸出是否準備好
       int temp = 0 ;    
       try{
         while((temp=input.read())!=-1){   // 開始拷貝
          out.write(temp) ;   // 邊讀邊寫
        }
        System.out.println( "拷貝完成!") ;
      } catch(IOException e){
        e.printStackTrace() ;
        System.out.println( "拷貝失敗!") ;
      }
       try{
        input.close() ;     // 關閉
        out.close() ;     // 關閉
      } catch(IOException e){         e.printStackTrace() ;       }     }   }     }
相關文章
相關標籤/搜索