---
title: "(转)文件或文件夹拷贝（源代码）"
author: "7090"
date: "2011-03-30T13:53:19Z"
tags: [".net", "Web"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-05-04T11:46:54Z"
id: 980444
url: "https://7090.iteye.com/blog/980444"
---

原文载于：[http://www.blogjava.net/web/](http://www.blogjava.net/web/)

// 任务：  
// 写一个文件拷贝函数： fileCopy(String a ,String b)     
// a--表示原文件名   b--表示目标文件名扩展：  
// 如果a是文件，则copy a到b ;  
// 如果a是目录，则递归copy a下的所有文件和文件夹（包括子文件夹）到b目录下。  
//

import  java.io. * ;

public   class  IODemo {  
      
     public   void  fileCopy(String a, String b){  
        File file  =   new  File(a);

         if ( ! file.exists()){  
            System.out.println(a  +   "  Not Exists. " );  
             return ;  
        }  
        File fileb  =   new  File(b);

         if (file.isFile()){  
            FileInputStream fis  =   null ;  
            FileOutputStream fos  = null ;  
             try  {  
                fis  =   new  FileInputStream(file);  
                fos  =    new  FileOutputStream(fileb);  
                  
                 byte \[] bb  = new   byte \[ ( int )file.length()];  
                fis.read(bb);  
                fos.write(bb);

            } catch  (IOException e){  
                e.printStackTrace();  
            } finally {  
                 try  {  
                    fis.close();  
                    fos.close();  
                }  catch  (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        } else   if (file.isDirectory()){  
             if ( ! fileb.exists()){  
                fileb.mkdir();  
            }  
            String\[] fileList;  
            fileList  =  file.list();  
             for ( int  i  =   0 ; i  &lt;  fileList.length; i ++ ){  
                fileCopy(a  +   " \\\\ "   +  fileList\[i],b  +   " \\\\ "   +  fileList\[i]);  
            }  
        }  
    }  
      
}