Skip to content

Latest commit

 

History

History
82 lines (74 loc) · 2.09 KB

复制文件或文件夹.md

File metadata and controls

82 lines (74 loc) · 2.09 KB

将文件或文件夹从一个位置复制到另一个位置

代码

复制文件

  /**
   * 拷贝两个文件的内容
   *
   * @param from 源文件
   * @param to 目标文件
   */
  public static void copyFile(File from, File to) {
    FileInputStream fromIs = null;
    FileOutputStream toOs = null;
    FileChannel fromChannel = null;
    FileChannel toChannel = null;
    try {
      if (!to.exists()) {
        to.createNewFile();
      }
      fromIs = new FileInputStream(from);
      toOs = new FileOutputStream(to);
      fromChannel = fromIs.getChannel();
      toChannel = toOs.getChannel();
      fromChannel.transferTo(0, fromChannel.size(), toChannel);
    } catch (IOException e) {
      throw new RuntimeException(e);
    } finally {
      close(fromChannel);
      close(fromIs);
      close(toChannel);
      close(toOs);
    }
  }

  public static void close(Closeable closeable) {
    if (closeable != null) {
      try {
        closeable.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }

复制文件夹

  /**
   * 目录内容拷贝,只拷贝文件内部的文件及文件夹
   *
   * @param from 源目录
   * @param to 目标目录
   */
  public static void copyDir(File from, File to) {
    String[] list;
    if (!from.isDirectory() || (list = from.list()) == null) {
      return;
    }
    String fromPath = from.getAbsolutePath();
    String toPath = to.getAbsolutePath();

    for (String filename : list) {
      String fromFilepath = fromPath + File.separator + filename;
      String toFilepath = toPath + File.separator + filename;
      File fromFile = new File(fromFilepath);
      File toFile = new File(toFilepath);
      if (fromFile.isDirectory()) {
        // 如果赋值的是文件夹,则创建该文件夹, 并进入文件夹内部拷贝文件
        toFile.mkdirs();
        copyDir(fromFile, toFile);
      } else {
        // 拷贝文件内容
        copyFile(fromFile, toFile);
      }
    }
  }