`

java 文件夹拷贝(文件夹里包含文件和文件夹) 代码

 
阅读更多
java代码实现文件夹拷贝,文件夹可能包含文件夹和文件



01.import java.io.BufferedReader; 
02.import java.io.File; 
03.import java.io.FileInputStream; 
04.import java.io.FileNotFoundException; 
05.import java.io.FileOutputStream; 
06.import java.io.IOException; 
07.import java.io.InputStreamReader; 
08.import java.io.PrintStream; 
09. 
10./**
11. * @author 孙潇
12. * 文件夹拷贝(文件内含有文件和文件夹)
13. *
14. */ 
15.public class CopyDirectory { 
16.     
17.    public static void main(String[] args) { 
18.        copy("F:\\myjava","E:\\myjava"); 
19.        System.out.println("文件拷贝完成!"); 
20.    } 
21. 
22.    private static void copy(String src, String des) { 
23.        File file1=new File(src); 
24.        File[] fs=file1.listFiles(); 
25.        File file2=new File(des); 
26.        if(!file2.exists()){ 
27.            file2.mkdirs(); 
28.        } 
29.        for (File f : fs) { 
30.            if(f.isFile()){ 
31.                fileCopy(f.getPath(),des+"\\"+f.getName()); //调用文件拷贝的方法 
32.            }else if(f.isDirectory()){ 
33.                copy(f.getPath(),des+"\\"+f.getName()); 
34.            } 
35.        } 
36.         
37.    } 
38. 
39.    /**
40.     * 文件拷贝的方法
41.     */ 
42.    private static void fileCopy(String src, String des) { 
43.     
44.        BufferedReader br=null; 
45.        PrintStream ps=null; 
46.         
47.        try { 
48.            br=new BufferedReader(new InputStreamReader(new FileInputStream(src))); 
49.            ps=new PrintStream(new FileOutputStream(des)); 
50.            String s=null; 
51.            while((s=br.readLine())!=null){ 
52.                ps.println(s); 
53.                ps.flush(); 
54.            } 
55.             
56.        } catch (FileNotFoundException e) { 
57.            // TODO Auto-generated catch block 
58.            e.printStackTrace(); 
59.        } catch (IOException e) { 
60.            // TODO Auto-generated catch block 
61.            e.printStackTrace(); 
62.        }finally{ 
63.             
64.                try { 
65.                    if(br!=null)  br.close(); 
66.                    if(ps!=null)  ps.close(); 
67.                } catch (IOException e) { 
68.                    // TODO Auto-generated catch block 
69.                    e.printStackTrace(); 
70.                } 
71.                 
72.        } 
73.         
74.         
75.    } 
76. 
77.} 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics