- package com.kxg_2;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- /*
- * 需求:复制多级文件夹D:\Test到D:\Test2里面
- */
- public class Copy3 {
- public static void main(String[] args) throws IOException {
- // 封装数据源
- File srcFile = new File("D:\\Test");
- // 封装目的地
- File destFile = new File("c:\\");
- // 如果没有目的地文件夹就创建
- if (!destFile.exists()) {
- destFile.mkdir();
- }
- copyFolder(srcFile, destFile);
- }
- private static void copyFolder(File srcFile, File destFile)
- throws IOException {
- // 判断是否文件夹
- if (srcFile.isDirectory()) {
- // 是文件就在目的地文件夹中创建这个文件夹
- File newFolder = new File(destFile, srcFile.getName());
- newFolder.mkdir();
- // 获取此文件夹中File对象数组
- File[] fileArray = srcFile.listFiles();
- // 遍历所有File对象,并递归
- for (File file : fileArray) {
- copyFolder(file, newFolder);
- }
- // 是文件就复制到目的地目录中去
- } else {
- File newFile = new File(destFile, srcFile.getName());
- copyFile(srcFile, newFile);
- }
- }
- private static void copyFile(File srcFile, File newFile) throws IOException {
- BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
- srcFile));
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
-
- byte[] bys = new byte[1024];
- int len =0;
- while((len=bis.read(bys))!=-1)
- {
- bos.write(bys,0,len);
- }
- bis.close();
- bos.close();
- }
- }
复制代码
|
|