zoukankan      html  css  js  c++  java
  • IO流的练习2 —— 复制单级文件夹中的文件

    需求:把C:UsersAdministratorDesktop记录测试里面的所有文件复制到
        C:UsersAdministratorDesktop新建文件夹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:UsersAdministratorDesktop记录测试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     }
    何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
  • 相关阅读:
    android canvas drawtext 字高
    ios修改UIIMage大小
    聊聊视频播放那些事2
    聊聊视频播放那些事1
    重入锁 ReentrantLock (转)(学习记录)
    setHasFixedSize(true)的意义 (转)
    ActivityLifecycleCallbacks
    NSSet
    阿里云ECS服务器IIS和WampServer同时运行
    ASP.NET MVC4网站部署在阿里ECS云服务器(WIndows Server 2012+IIS8环境)
  • 原文地址:https://www.cnblogs.com/LZL-student/p/5927193.html
Copyright © 2011-2022 走看看