IO流的练习2 —— 复制单级文件夹中的文件

需求:把C:\Users\Administrator\Desktop\记录\测试里面的所有文件复制到
    C:\Users\Administrator\Desktop\新建文件夹\copy文件夹中
分析:
    A:封装目录
    B:获取该目录下的所有文件的File数组
    C:遍历该集合,得到每一个File对象
    D:把每个File复制到目的文件夹中

 

 1     public static void main(String[] args) throws IOException {
 2         // 封装目录
 3         File start = new File("C:\\Users\\Administrator\\Desktop\\记录\\测试");
 4         File end = new File("C:\\Users\\Administrator\\Desktop\\新建文件夹\\copy");
 5         //如果目的文件夹不存在,则创建
 6         if(!end.exists()){
 7             end.mkdir();
 8         }
 9         
10         //得到start目录下的所有文件的File数组
11         File[] f = start.listFiles();
12         //遍历数组,得到每一个file对象
13         for(File file : f){
14             //System.out.println(f);
15             //数据源——————C:\Users\Administrator\Desktop\记录\测试\Student.class 其中的一个
16             //System.out.println(f.getName());//Student.class
17             //目的地------C:\\Users\\Administrator\\Desktop\\新建文件夹\\copy\\Student.class
18             
19             //为了在目的文件夹中创建这样的文件,就得用拼接,把end和文件名拼接起来
20             String name = file.getName();
21             File newfile = new File(end,name);//File的第三种构造方法
22             
23             //把数据源中文件的数据复制到目的文件中
24             copyfile(file,newfile);
25         }
26 
27     }
28 
29     private static void copyfile(File file, File newfile) throws IOException {
30         // 把file中的数据复制到newfile中,因为任何类型文件都复制,所以用缓冲字节流
31         BufferedInputStream bi = new BufferedInputStream(new FileInputStream(file));
32         BufferedOutputStream bo = new BufferedOutputStream (new FileOutputStream(newfile));
33         //读一个字节数组的方式:
34         byte[] by = new byte[1024];
35         int len = 0;
36         while((len = bi.read(by)) != -1){
37             bo.write(by,0,len);
38         }
39         bi.close();
40         bo.close();
41     }

 

posted @ 2016-10-02 09:36  卡拉瓦  阅读(684)  评论(0编辑  收藏  举报