- package com.heima.test;
- 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 Test3 {
- public static void main(String[] args) throws IOException {
- //获取两个文件夹路径
- File yuan = Test.getDir();
- File des = Test.getDir();
- if(yuan.equals(des)){
- System.out.println("目标文件夹是源文件夹的子文件夹");
-
- }
-
- //调用方法,进行复制
- method(yuan,des);
-
- }
- public static void method(File yuan, File des) throws IOException {
- //在目标文件夹中创建原文件夹
- File newf = new File(des,yuan.getName());
- newf.mkdirs();
- //创建File数组,添加原路径下的文件夹和文件,遍历
- File[] f1 = yuan.listFiles();
-
- if (f1 == null){
- return;
- }
- for (File f2 : f1) {
- //如果是文件的话,就复制
- if (f2.isFile()){
- copy(newf, f2);
- }
-
- //如果是文件夹的话,递归
- if(f2.isDirectory()){
- method(f2,newf);
- }
- }
- }
-
-
- public static void copy(File newf, File f2) throws FileNotFoundException,
- IOException {
- BufferedInputStream bis =
- new BufferedInputStream(new FileInputStream(f2));
- BufferedOutputStream bos =
- new BufferedOutputStream(new FileOutputStream(new File(newf,f2.getName())));
- int b;
- while((b=bis.read())!=-1){
- bos.write(b);
- }
-
- bis.close();
- bos.close();
- }
- }
复制代码 |
|