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的自学历程...只需坚持
  • 相关阅读:
    附近有什么?8款可以查周边的App
    实体店里充话费要怎么弄
    怎样买手机号?
    手机号是SIM卡的号呢,还是买手机时就带的
    网站SSL证书在线检测
    未来什么行业最赚钱
    陈安之-如何选择最赚钱的行业
    斗鱼宣布获C轮15亿融资 直播行业进入资本时代
    2016年Godaddy最新域名转出教程
    GoDaddy账户间域名转移PUSH以及ACCEPT接受域名过户方法
  • 原文地址:https://www.cnblogs.com/LZL-student/p/5927193.html
Copyright © 2011-2022 走看看