1 /**
2 * 功能描述:拷贝一个目录或者文件到指定路径下,即把源文件拷贝到目标文件路径下
3 *
4 * @param source
5 * 源文件
6 * @param target
7 * 目标文件路径
8 * @return void
9 */
10 public static void copy(File source, File target) {
11 File tarpath = new File(target, source.getName());
12 if (source.isDirectory()) {
13 tarpath.mkdir();
14 File[] dir = source.listFiles();
15 for (int i = 0; i < dir.length; i++) {
16 copy(dir[i], tarpath);
17 }
18 } else {
19 try {
20 InputStream is = new FileInputStream(source); // 用于读取文件的原始字节流
21 OutputStream os = new FileOutputStream(tarpath); // 用于写入文件的原始字节的流
22 byte[] buf = new byte[1024];// 存储读取数据的缓冲区大小
23 int len = 0;
24 while ((len = is.read(buf)) != -1) {
25 os.write(buf, 0, len);
26 }
27 is.close();
28 os.close();
29 } catch (FileNotFoundException e) {
30 e.printStackTrace();
31 } catch (IOException e) {
32 e.printStackTrace();
33 }
34 }
35 }