Java语言使用io流实现文件夹的复制

功能:复制文件夹
技能:IO流进行文件的复制  创建文件夹 dir.mkdirs();  递归

问题1:使用字节流还是字符流
   字节流 因为有二进制文件
问题2:提高复制的速度
   缓冲流 BufferedInputStream BufferedOutputStream
  中转站:一个字节------>一个字节数组
问题3:问题分解
    分解1:复制一个文件
    分解2:复制一个文件夹下的所有的文件(不包括子文件夹)
    分解3:复制一个文件夹下的所有的文件和子文件夹(也包括子文件夹下内容)z


import java.io.*;

public class TestCopyDir {
    public static void main(String[] args) {
//        copyFile("d:/hello.txt", "d:/hello1.txt");
        copyDir("D:/hello", "D:/hello2");
    }

    //复制文件夹
    public static void copyDir(String sourceDirName, String destDirName) {
        //创建目的文件夹
        File destDir = new File(destDirName);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }

        //获取源文件夹下所有的文件和文件夹并复制
        File sourceDir = new File(sourceDirName);
        if (!sourceDir.exists()) {
            System.out.println("源文件夹:[" + sourceDirName + "]不存在!");
            return;
        }

        File[] files = sourceDir.listFiles();
        for (File file : files) {
            //如果是文件,就复制
            if (file.isFile()) {
                System.out.println("----------正在复制文件:" + file.getName() + "---------------");
                //复制文件
                copyFile(sourceDirName + "/" + file.getName(), destDirName + "/" + file.getName());
            }
            //如果是文件夹,就复制
            if (file.isDirectory()) {
                System.err.println("----------正在复制文件夹:" + file.getName() + "---------------");
                copyDir(sourceDirName + "/" + file.getName(), destDirName + "/" + file.getName());
            }
        }
    }

    //复制文件
    public static void copyFile(String sourceFileName, String destFileName) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //创建一个输入流和一个输出流
            bis = new BufferedInputStream(new FileInputStream(new File(sourceFileName)));
            bos = new BufferedOutputStream(new FileOutputStream(new File(destFileName)));

            //使用一个输入流(读)和一个输出流(写)
            byte[] bytes = new byte[1024];//中转站
            int len = 0;
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭一个输入流和一个输出流
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}