zoukankan      html  css  js  c++  java
  • Java基础知识强化之IO流笔记48:IO流练习之 复制单级文件夹案例

    1. 复制单级文件夹

        数据源:e:\demo

        目的地:e:\test

    分析:
      A封装目录
      B获取该目录下的所有文本的File数组
      C遍历该File数组,得到每一个File对象
      D把该File进行复制

    2.  代码示例:

     1 package cn.itcast_03;
     2 
     3 import java.io.BufferedInputStream;
     4 import java.io.BufferedOutputStream;
     5 import java.io.File;
     6 import java.io.FileInputStream;
     7 import java.io.FileOutputStream;
     8 import java.io.IOException;
     9 
    10 /*
    11  * 需求:复制单极文件夹
    12  * 
    13  * 数据源:e:\demo
    14  * 目的地:e:\test
    15  * 
    16  * 分析:
    17  *         A:封装目录
    18  *         B:获取该目录下的所有文本的File数组
    19  *         C:遍历该File数组,得到每一个File对象
    20  *         D:把该File进行复制
    21  */
    22 public class CopyFolderDemo {
    23     public static void main(String[] args) throws IOException {
    24         // 封装目录
    25         File srcFolder = new File("e:\demo");
    26         // 封装目的地
    27         File destFolder = new File("e:\test");
    28         // 如果目的地文件夹不存在,就创建
    29         if (!destFolder.exists()) {
    30             destFolder.mkdir();
    31         }
    32 
    33         // 获取该目录下的所有文本的File数组
    34         File[] fileArray = srcFolder.listFiles();
    35 
    36         // 遍历该File数组,得到每一个File对象
    37         for (File file : fileArray) {
    38             // System.out.println(file);
    39             // 数据源:e:\demo\e.mp3
    40             // 目的地:e:\test\e.mp3
    41             String name = file.getName(); // e.mp3
    42             File newFile = new File(destFolder, name); // e:\test\e.mp3
    43 
    44             copyFile(file, newFile);
    45         }
    46     }
    47 
    48     private static void copyFile(File file, File newFile) throws IOException {
    49         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
    50                 file));
    51         BufferedOutputStream bos = new BufferedOutputStream(
    52                 new FileOutputStream(newFile));
    53 
    54         byte[] bys = new byte[1024];
    55         int len = 0;
    56         while ((len = bis.read(bys)) != -1) {
    57             bos.write(bys, 0, len);
    58         }
    59 
    60         bos.close();
    61         bis.close();
    62     }
    63 }
  • 相关阅读:
    Ubuntu安装软件问题的解决
    寻找两个字符串中最长的公共部分字符串
    CentOS
    vim自定义配置
    git创建远程仓库以及在本地提交到远程仓库的方法
    黑金开发板在NiosII环境下烧写image到flash失败的解决办法
    f.lux 一款免费的护眼开源软件
    python 制作自动化脚本
    修改python 默认的存储路径
    第一篇博客
  • 原文地址:https://www.cnblogs.com/hebao0514/p/4870121.html
Copyright © 2011-2022 走看看