原创  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();
                }
            }
        }

    }
}

发表于 @ 2007年06月21日 08:54:00 | 评论( loading... ) | 编辑| 举报| 收藏

旧一篇:System.IO 路径,文件,目录,I/O常见操作汇总(二)  | 新一篇:打了一份程序员工作,感觉很适合自已

  • 发表评论
  • 评论内容:
  •  
Copyright © lxf9601
Powered by CSDN Blog