1 package IoTest;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileNotFoundException;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8
9 //对目录的复制
10 public class DirecitryCopyTest1 {
11 public static void main(String[] args){
12 File from=new File("D:/JAVA/File/copytest"); //源目录
13 File to=new File("C:/Users/hp/Desktop/CT"); //目标目录
14 //调用复制函数
15 copy(from,to);
16 System.out.println("复制成功!!!");
17 }
18 //复制函数编写
19 public static void copy(File from,File to){
20 //如果目录下存在文件,则进行文件的复制操作
21 if(from.isFile()){
22 FileInputStream fi=null;
23 FileOutputStream fo=null;
24 try {
25 fi=new FileInputStream(from.getAbsolutePath()); //源文件地址
26 fo=new FileOutputStream(to.getAbsolutePath()+from.getAbsolutePath().substring(2)); //目标文件地址
27 byte[] bytes=new byte[1024*1024]; //定义一个1M的byte组来存放读出来的数据
28 int readIndex;
29 //进行读写操作:边读边写
30 while((readIndex=fi.read(bytes))!=-1){
31 fo.write(bytes, 0, readIndex);
32 }
33 fo.flush();//刷新
34 } catch (FileNotFoundException e) {
35 e.printStackTrace();
36 } catch (IOException e) {
37 e.printStackTrace();
38 }finally{
39 if(fi!=null){
40 try {
41 fi.close();
42 } catch (IOException e) {
43 e.printStackTrace();
44 }
45 if(fo!=null){
46 try {
47 fo.close();
48 } catch (IOException e) {
49 e.printStackTrace();
50 }
51 }
52 }
53 }
54
55 return;
56 }
57 File[] files=from.listFiles();
58 for(File file:files){
59 File newFile=new File(to.getAbsolutePath()+from.getAbsolutePath().substring(2));
60 //在目标位置编写文件目录
61 if(!newFile.exists()){
62 newFile.mkdirs();
63 }
64 //利用递归来获取目录中子目录中的文件
65 copy(file,to);
66 }
67
68 }
69
70 }