0
点赞
收藏
分享

微信扫一扫

Java中实现复制文件或文件夹


拷贝一个文件的算法比较简单,当然,可以对它进行优化,比如使用缓冲流,提高读写数据的效率等。但是在复制文件夹时,则需 要利用Flie


1.  import   java.io.*;     
2.     
3.  public    class   CopyDirectory {    
4. // 源 文件夹 
5.       static   String url1 =  "f:/photos"
6. // 目 标文件夹 
7.       static   String url2 =  "d:/tempPhotos"
8.       public    static    void   main(String args[])  throws   IOException {    
9. // 创建目标文件夹 
10.          ( new   File(url2)).mkdirs();    
11. // 获取源文件夹当前下的文件或目录 
12.          File[] file = ( new   File(url1)).listFiles();    
13.           for   ( int   i =  0
14.               if   (file[i].isFile()) {    
15. // 复制文件 
16.                  copyFile(file[i], new   File(url2+file[i].getName()));    
17.              }    
18.               if   (file[i].isDirectory()) {    
19. // 复制目录 
20.                  String sourceDir=url1+File.separator+file[i].getName();    
21.                  String targetDir=url2+File.separator+file[i].getName();    
22.                  copyDirectiory(sourceDir, targetDir);    
23.              }    
24.          }    
25.      }    
26. // 复制文件 
27.  public    static    void   copyFile(File sourceFile,File targetFile)     
28.  throws   IOException{    
29. // 新建文件输入流并对它进行缓冲 
30.          FileInputStream input =  new   FileInputStream(sourceFile);    
31.          BufferedInputStream inBuff= new   BufferedInputStream(input);    
32.     
33. // 新建文件输出流并对它进行缓冲 
34.          FileOutputStream output =  new   FileOutputStream(targetFile);    
35.          BufferedOutputStream outBuff= new   BufferedOutputStream(output);    
36.              
37. // 缓冲数组 
38.           byte  [] b =  new    byte  [ 1024   *  5
39.           int   len;    
40.           while   ((len =inBuff.read(b)) != - 1
41. 0
42.          }    
43. // 刷新此缓冲的输出流 
44.          outBuff.flush();    
45.              
46. //关闭流 
47.          inBuff.close();    
48.          outBuff.close();    
49.          output.close();    
50.          input.close();    
51.      }    
52. // 复 制文件夹 
53.       public    static    void   copyDirectiory(String sourceDir, String targetDir)    
54.               throws   IOException {    
55. // 新建目标目录 
56.          ( new   File(targetDir)).mkdirs();    
57. // 获取源文件夹当前下的文件或目录 
58.          File[] file = ( new   File(sourceDir)).listFiles();    
59.           for   ( int   i =  0
60.               if   (file[i].isFile()) {    
61. // 源文件 
62.                  File sourceFile=file[i];    
63. // 目标文件 
64.                 File targetFile= new       
65.  File( new   File(targetDir).getAbsolutePath()    
66.  +File.separator+file[i].getName());    
67.                  copyFile(sourceFile,targetFile);    
68.              }    
69.               if   (file[i].isDirectory()) {    
70. // 准备复制的源文件夹 
71. "/"
72. // 准备复制的目标文件夹 
73. "/"
74.                  copyDirectiory(dir1, dir2);    
75.              }    
76.          }    
77.      }    
78.  }

举报

相关推荐

0 条评论