IO流应用-文件夹的复制

来源:互联网 发布:海盗战 知乎 编辑:程序博客网 时间:2024/05/16 08:19
import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;//编写一个程序实现 一个文件夹的复制。public class Test4 {    public static void main(String[] args) {        String path1 = "E:/ProgramData";        String path2 = "D:/a";        System.out.println("正在复制请稍后...");        long t1 = System.currentTimeMillis();        copy1(path1, path2);        long t2 = System.currentTimeMillis();        System.out.println("您耗时" + (t2 - t1) + "毫秒完成了文件夹" + path1 + "的复制");    }    //单纯的文件复制    public static void copy(String path1, String path2) {        BufferedInputStream bis = null;        BufferedOutputStream bos = null;        byte[] b = new byte[100];        try {            bis = new BufferedInputStream(new FileInputStream(path1));            bos = new BufferedOutputStream(new FileOutputStream(path2));            int len;            while ((len = bis.read(b)) != -1) {                bos.write(b, 0, len);            }            bos.flush();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            if (bos != null) {                try {                    bos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (bis != null) {                try {                    bis.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    //含有文件夹的复制    public static void copy1(String path1, String path2) {        File f1 = new File(path1);        String name1 = f1.getName();// 获取要复制的文件夹名        File f2 = new File(path2 +"/"+ name1);//中间加上"/"使文件夹正确创建        f2.mkdir();// 创建文件夹        //获取文件及文件夹名称的字符串数组        String[] fn = f1.list();        for (String str : fn) {            //创建File对象,便于判断时文件还是文件夹            File f3 = new File(f1.getAbsolutePath()+ "/" + str);            //是文件就复制文件,是文件夹就创建文件夹            if (f3.isFile()) {                copy(f1.getAbsolutePath() + "/" + str, f2.getAbsolutePath() + "/" + str);            }else{                //创建子文件夹                File f4 = new File(f2.getAbsolutePath() + "/" + str);                f4.mkdir();                //重新给路径赋值,递归复制                path1 = f3.getAbsolutePath();                path2 = f4.getParent();//因为方法的上部用的path2 +"/"+ name1,所以此处要用父文件夹目录                copy1(path1, path2);            }        }    }}