星期二, 七月 03, 2007

copy file

package test;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;


public class test {

 
 public static void main(String args[]) {
  String filename1 = "C:\\1";
  String filename2 = "C:\\2";
  test test1 = new test();
  try{
  test1.copyFileByPath(filename1, filename2);
  }catch (Exception e) {
   // TODO: handle exception
  }
 }
 
 public void copyFileByPath(String scrPathName,String targetPathName)
  throws NullPointerException,IOException, Exception {
  try{
   File scrPath = new File(scrPathName);
   File targetPath = new File(targetPathName);
   copyFileByPath(scrPath, targetPath);
  }catch (NullPointerException e) {
   //logger.error(dir.getName() + " folder is not exist", e);
   throw e;
  } catch (IOException e) {
   //logger.error(e.getMessage(),e);
   throw e;
  }catch (Exception e) {
   //logger.error(e.getMessage(), e);
   throw e;
  }
 }
 public void copyFileByPath(File scrPath,File targetPath)
  throws NullPointerException,IOException, Exception {
  try {
   String[] fs = scrPath.list();

   for (int i = 0; i < fs.length; i++) {
    File fis = new File(scrPath, fs[i]);
    long currentTime = Calendar.getInstance().getTimeInMillis();
    if (fis.isFile()&&fis.lastModified()<(currentTime-1000*60*1)) {
     copyFile(fis, targetPath);
    } else if (fis.isDirectory()) {
     copyFileByPath(fis, targetPath);
    }
   }
  } catch (NullPointerException e) {
   //logger.error(dir.getName() + " folder is not exist", e);
   throw e;
  } catch (IOException e) {
   //logger.error(e.getMessage(),e);
   throw e;
  }catch (Exception e) {
   //logger.error(e.getMessage(), e);
   throw e;
  }
 }
 
 public void copyFile(File scrFile,File targetPath){
  long lastModifiedTime = scrFile.lastModified();
  
  try{
  File targetFile = new File(targetPath,scrFile.getName());
  java.io.FileInputStream in =new java.io.FileInputStream(scrFile);
     java.io.FileOutputStream out =new java.io.FileOutputStream(targetFile);
     byte Buff[]=new byte[1024];
     int len;
     while((len=in.read(Buff))>-1){
       out.write(Buff,0,len);
     }
     in.close();
     out.close ();
     targetFile.setLastModified(lastModifiedTime);
  }catch (Exception e) {
   // TODO: handle exception
  }
 }
}

没有评论: