Java递归实现文件夹Copy

package holiday.day09;

import java.io.File;

/**
 * 递归实现文件夹Copy
 */
public class FolderCopy {
    public static void main(String[] args) {

        copyFolder("D:/图片","F:/File");
    }

    public static void copyFolder(String originalPath, String ectyPath){    //源文件路径、目标路径
        File original = new File(originalPath);

        deep(original,ectyPath);

    }

    public static void deep(File src, String ectype){
        if (src==null || !src.exists()){
            return;
        }else if(src.isDirectory()){
            String namepath = ectype+"/"+src.getName();
            File dest = new File(namepath);
            boolean flag = dest.mkdirs();
            for(File temp:src.listFiles()){
                deep(temp, namepath);
            }
        }else{
            FileCopy.copy(src.getAbsolutePath(),ectype+"/"+src.getName());
        }
    }
    public static void copy(String srcPath, String destPath){

        File src = new File(srcPath);
        File dest = new File(destPath);
        InputStream is = null;
        OutputStream os = null;
        //int temp;
        try {
            is = new BufferedInputStream(new FileInputStream(src));  //操作(分段读取)
            os = new BufferedOutputStream(new FileOutputStream(dest));
            int len=-1;
            byte[] flush = new byte[1024];

            while((len=is.read(flush))!=-1){
                os.write(flush,0,len);
                os.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();

        }finally {
            if(null!=os){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }    
    
}

文件字节流可以处理所有的文件,但是字节流不能很好的处理Unicode字符,经常会出现“乱码”现象。所以,我们处理文本文件,一般可以使用文件字符流,它以字符为单位进行操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值