China.JAVA

Prefessional JAVA
posts - 0, comments - 0, trackbacks - 0, articles - 1

Java 文件夹考贝类( Java direcotry copy class)

Posted on 2005-12-16 17:03 cl.kcitwm 阅读(230) 评论(0)  编辑  收藏 所属分类: JAVA

package com.kcitwm.util;
/**
 * <p>Title: Direcotry copy </p>
 * <p>Description: Direcotry copy</p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: cime</p>
 * @author cl.kcitwm
 * @version 1.0
 * @mail   kcitwm@gmail.com
 */
import java.io.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 

public class FileCopy implements Runnable{
 
 private static final Log log=LogFactory.getLog(FileCopy.class);
 
 private String sourceDir;
 private String destDir;
 private int total=0;
 
 public void copy(String sourceDir,String destDir){  
  this.sourceDir=sourceDir;
  this.destDir=destDir;   
  Thread thread=new Thread(this);
  thread.start();  
 }
 
 private void copyDir(String sourceDir,String destDir) throws Exception{
  File sourceFile=new File(sourceDir);
  if(!sourceFile.exists())
   throw new IOException("source directory is not exists!");
  if(sourceFile.isFile())
   throw new IOException("source directory is not directory!"); 
  
  File destFile=new File(destDir);
  if(!destFile.exists())
   destFile.mkdir();
  
  String tempSource;
  String tempDest;
  String fileName;
  File[] files=sourceFile.listFiles();
  for(int i=0;i<files.length;i++){
   fileName=files[i].getName();
   tempSource=sourceDir+"/"+fileName;
   tempDest=destDir+"/"+fileName;
   if(files[i].isFile()){
    try{
     copyFile(tempSource,tempDest); 
      ++total;
    }
    catch(Exception e){
     
    }
   }
   else{
    copyDir(tempSource,tempDest);
   }
  }
  sourceFile=null;
  destFile=null;  
 }
 
 private void copyFile(String source,String dest) throws Exception {  
   File d=new File(dest);
   File s=new File(source);
   if(d.exists() && d.lastModified()==s.lastModified())
    return; 
   FileInputStream fis=new FileInputStream(s);
   FileOutputStream fos=new FileOutputStream(d); 
   byte[] buffer=new byte[1024*4];
   int n=0;
   while((n=fis.read(buffer))!=-1){
    fos.write(buffer,0,n);
   }
   fis.close();
   fos.close();
   buffer=null;
   s=null;
   d=null;
 }
 
 public void run(){
  try{   
   copyDir(sourceDir,destDir);
   log.info(total+" files updated from "+sourceDir+" to "+destDir);
   
  }
  catch(Exception e){
   log.error(e);
  }
 }
 
}


只有注册用户登录后才能发表评论。


网站导航: