1 package com.hxl;
2
3 import java.io.BufferedInputStream;
4 import java.io.BufferedOutputStream;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9
10 /**
11 *
12 * @author Schiller_Hu
13 * @version v1.0
14 *
15 * 分析:
16 * A:封装数据源File
17 * B:封装数据目的地File
18 * C:判断该File是文件夹还是文件
19 * a:是文件夹
20 * 就在目的地目录创建该文件夹
21 * 获取该File对象下的所有文件或者文件夹File对象 遍历得到每一个File对象
22 * 回到C
23 * b:是文件
24 * 直接复制
25 *
26 */
27 public class Test {
28 public static void main(String[] args) throws IOException {
29 // 源路径
30 File srcFile = new File("E:\\工作学习\\计算机杂类\\Java Web开发\\Web基础\\JavaScript & jQuery精品教程视频");
31 // 目标路径
32 File destFile = new File("E:\\");
33 // 调用方法
34 copyFolder(srcFile, destFile);
35 }
36
37 public static void copyFolder(File srcFile, File destFile) throws IOException {
38 // 判断File对象是否是文件夹
39 if (srcFile.isDirectory()) {
40 // 拼接新文件夹所在路径
41 File newFolder = new File(destFile, srcFile.getName());
42 // 创建文件夹
43 newFolder.mkdir();
44 // 遍历源路径下的所有File对象
45 File[] fileArray = srcFile.listFiles();
46 for (File file : fileArray) {
47 // 递归调用
48 copyFolder(file, newFolder);
49 }
50 } else {
51 // 拼接新文件所在路径
52 File newFile = new File(destFile, srcFile.getName());
53 // 调用方法,复制文件
54 copyFile(srcFile, newFile);
55 }
56 }
57
58 // 高效字节流一次读取一个字节数组复制文件
59 public static void copyFile(File srcFile, File newFile) throws IOException {
60 // 数据源
61 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
62 srcFile));
63 // 目的位置
64 BufferedOutputStream bos = new BufferedOutputStream(
65 new FileOutputStream(newFile));
66 // 定义单次读取字节数组的大小,一般就写1024
67 byte[] bys = new byte[1024];
68 // read(byte[] bys)方法返回值为获取到的字节个数,若没有获取到,则返回-1
69 int length = 0;
70 while ((length = bis.read(bys)) != -1) {
71 // write(byte[] bys,int off,int length)方法指的是从指定字节数组的指定位置开始写入(复制到)文件
72 bos.write(bys, 0, length);
73 }
74 // 关闭输出流
75 bos.close();
76 // 关闭输入流
77 bis.close();
78 }
79 }