文件和目录复制函数

[转载]文件和目录复制函数
http://spaces.msn.com/members/kliweik/

今天偷懒,要Roy帮我写了一个目录复制的函数,记录,备后用,呵呵!

/* Created on  2005 - 8 - 8  
 * 
 * @author wei.li  
 * TODO 用来运行外部命令的工具类 */
package com.linktone.photo.lucene
;

import java.io.File
;
import java.io.FileInputStream ;
import java.io.FileOutputStream ;
import java.io.IOException ;
import java.nio.channels.FileChannel ;

public class FileUtil {
    /** * 功能:利用nio来快速复制文件 */
    public static void copyFile(String srcFile
,  String destFile)
            throws java.io.FileNotFoundException
,  java.io.IOException {
        FileInputStream fis 
=  new FileInputStream(srcFile) ;
        FileOutputStream fos  =  new FileOutputStream(destFile) ;
        FileChannel fcin  =  fis.getChannel() ;
        FileChannel fcout  =  fos.getChannel() ;
        fcin.transferTo( 0 ,  fcin.size() ,  fcout) ;
        fcin.close() ;
        fcout.close() ;
        fis.close() ;
        fos.close() ;
    }

    /** * 功能:利用nio快速复制目录 */
    public static void copyDirectory(String srcDirectory
,  String destDirectory)
            throws java.io.FileNotFoundException
,  java.io.IOException { // 得到目录下的文件和目录数组
        File srcDir 
=  new File(srcDirectory) ;
        File []  fileList  =  srcDir.listFiles() ;
        // 循环处理数组
        for (int i 
=   0 ;  i < fileList.length; i++) {
            if (fileList [ i ] .isFile()) {
                // 数组中的对象为文件
                // 如果目标目录不存在,创建目标目录
                File descDir 
=  new File(destDirectory) ;
                if (!descDir.exists()) {
                    descDir.mkdir()
;
                } // 复制文件到目标目录
                copyFile(srcDirectory + 
" / "  + fileList [ i ] .getName() ,
                        destDirectory + 
" / "  + fileList [ i ] .getName()) ;
            } else {
                // 数组中的对象为目录
                // 如果该子目录不存在就创建(其中也包含了对多级目录的处理)
                File subDir 
=  new File(destDirectory +  " / "
                        + fileList
[ i ] .getName()) ;
                if (!subDir.exists()) {
                    subDir.mkdir()
;
                }
                // 递归处理子目录
                copyDirectory(srcDirectory + 
" / "  + fileList [ i ] .getName() ,
                        destDirectory + 
" / "  + fileList [ i ] .getName()) ;

            }
        }
    }

    public static void main(String
[]  args) throws IOException {

        FileUtil.copyDirectory(
" e:/temp/index/test " ,   " e:/temp/index/test2 " ) ;
    }

}

你可能感兴趣的:(文件和目录复制函数)