Java实现Copy

 

假定源文件夹为D:/网络管理,目标文件夹为D:/网络管理2,将目录及子目录下的文件做拷贝

package test;

import java.io.*;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 */
public class Copys {

    public static void main(String args[]) {
        File file = new File("D://网络管理");
        File tofile = new File("D://网络管理2");
        tofile.mkdirs();//建立目标文件夹

        //指定源文件夹和目标文件夹参数,调用toCopyf方法
        toCopyf(file, tofile);
    }
    /**
     * 持贝指定的目录下所有文件及子目录到目标文件夹
     * */
    public static void toCopyf(File file, File tofile) {
       
        //获取源目录下一级所有目录文件
        File[] files = file.listFiles();
        //逐个判断,创建目录,执行递归调用 
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                File copyPath = new File(tofile.getAbsolutePath() + "//" +
                                        files[i].getName());
                copyPath.mkdir();
                toCopyf(files[i],copyPath);
            } else {  //如果file为文件,读取字节流写入目标文件;
                try {
                    FileInputStream fiStream = new FileInputStream(files[i]);
                    BufferedInputStream biStream = new BufferedInputStream(
                            fiStream);
                    File copyFile = new File(tofile.getAbsolutePath()
                                           + "//" + files[i].getName());
                    copyFile.createNewFile();
                    FileOutputStream foStream = new FileOutputStream(copyFile);
                    BufferedOutputStream boStream = new BufferedOutputStream(
                            foStream);

                    int j;
                    while ((j = biStream.read()) != -1) {
                        boStream.write(j);
                    }
                   
                    /*关闭流*/                   
                    biStream.close();
                    boStream.close();
                    fiStream.close();
                    foStream.close();
                } catch (FileNotFoundException ex) {
                    ex.printStackTrace();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值