FileUtil-文件拷贝扩展版

FileUtil-文件拷贝扩展版 实现文件拷文件,文件拷文件夹,文件夹拷文件夹

  package cn.hjm.test;

  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
/**
 * 根据传入参数的类型调用不同的拷贝方法,实现重载
 * @author hjm
 * 可以实现文件夹拷文件夹,文件拷文件,文件拷文件夹 这几种操作
 *
 */
public class FileUtil {

/**
 * 
 * @param src
 * @param dest
 * @throws IOException
 */

public static void CopyFile(File src, File dest) throws IOException{
    InputStream is=null;
    OutputStream os = null;
    File destSecond=null;
    if(dest.isDirectory()){ //如果目标是一个文件夹,那么就在该dest文件夹下建立一个新的文件类型
        destSecond = new File(dest,src.getName()); //这一步如何制定文件的格式,因为单独的文件拷贝要指定双方的文件类型
        //实现文件拷文件夹中去
    
        os = new FileOutputStream(destSecond); //实现拷文件操作
    }else{
        //如果是个文件的话,直接拷贝
        os =new FileOutputStream(dest);
    }
    try {
        is = new FileInputStream(src);
    
        
        byte[] by = new byte[1024];//准备车子
        int len=0; //假设车上没有人
        
        try {
            while(-1!=(len=is.read(by))){ //开始慢慢下车和上车
                os.write(by, 0, len); //下车
            }
        } catch (IOException e) {
            e.printStackTrace();
            
        }finally{
            os.flush();
            is.close();
            os.close();
        }
        
        
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        System.out.println("文件未找到");
    }
}
/**
 * 
 * @param srcPath
 * @param destPath
 * @throws IOException
 */
public static void CopyFile(String srcPath,String destPath) throws IOException{
    CopyFile(new File(srcPath), new File(destPath));
}

/**
 * 文件夹的拷贝
 * @param src
 * @param dest
 */
public static void copyDir(String src,String dest){
    File srcPath =new File(src);
    File destPath = null;
    if(srcPath.isDirectory()){
        destPath = new File(dest,srcPath.getName());//如果源文件是个文件夹,那么现在目标文件夹下再建一个一样的文件夹
    }
    
    copyDirDetail(srcPath,destPath);
}

public static void copyDirDetail(File srcPath,File destPath){
    if(srcPath.isFile()){ //为下级做准备,这级估计用不到
        try {
            FileUtil.CopyFile(srcPath, destPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }else if(srcPath.isDirectory()){
        destPath.mkdir();//,建立它,确保目标文件夹存在
            File[] filelist = srcPath.listFiles();
            for(File file:filelist){
                copyDirDetail(file,new File(destPath,file.getName()));
            }
    }
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值