文件的复制

来源:互联网 发布:php彩票源码 编辑:程序博客网 时间:2024/05/18 00:15

 package text;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Admin
 * 文件的复制
 */
public class FileCopy {
   
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  copyFile(args[0],args[1]) ;
 }
   
 private static void copyFile(String sourceFileName ,String targetFileName) {
  
  File sourceFile = new File(sourceFileName) ;
  File targetFile = new File(targetFileName) ;
  
  if(!sourceFile.exists()) {
   System.out.println("源文件不存在");
  }
  if(!sourceFile.isFile()) {
   System.out.println("源文件不能复制");
//   System.out.println("目标文件不存在");
  }
     if(!sourceFile.canRead()) {
      System.out.println("源文件"+sourceFile+"不能读");
     }
     if(targetFile.isDirectory()){
      
      targetFile = new File(targetFile,sourceFile.getName()) ;
     }
     //如果目标文件存在则看他是否可写,并册在写之前询问用户
     //如果目标文件不存在,那么首先确定目录存在且可写
     if(targetFile.exists()) {
      if(!targetFile.canWrite()) {
       System.out.println("目标文件不是可写文件:"+targetFile);
      }
      //询问用户是否覆盖目标文件
      System.out.println("是否覆盖现有文件"+targetFile.getName()+"Y/N?");
      System.out.flush() ;
      //得到用户信息
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ;
      
      try {
    String response = in.readLine() ;
       //检测用户反馈信息
    //如果得到的是否则取消操作
    if(!response.equals("Y")&&!response.equals("y")) {
     System.out.println("用户取消复制操作");
    } else {
     String parent = targetFile.getParent() ;//目标目录
     if(parent == null){
      parent = System.getProperty("user.dir") ;
     }
     File dictory = new File(parent) ;//将它转换成文件
     if(!dictory.exists()) {
      System.out.println("目标目录不存在");
     }
     if(dictory.isFile()) {
      System.out.println("指定目标不是目录");
//      System.out.println("目标文件不存在");
     }
        if(!dictory.canWrite()) {
         System.out.println("指定目标"+dictory+"不能写的");
        }
       
        FileInputStream  resource = new FileInputStream(sourceFile) ;
        FileOutputStream  target = new FileOutputStream(targetFile) ;
        byte[] buffer = new byte[4*1024] ;
       
        int byteNum ;
        while((byteNum = resource.read(buffer)) != -1) {
         target.write(buffer,0,byteNum) ;
         System.out.println("文件复制成功!");
        }
    }
      } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }finally {
    try {
//     resource.close();
//     target.close() ;
     in.close() ;
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
     }
 }
}

原创粉丝点击