可能是最完美的Android复制拷贝文件的实例(Java NIO速度快)

此处我使用的是使用Java NIO中的管道到管道传输,包括了transferFrom方法。
经过测试比文件流复制的速度更快!

  private final static String FileName = "a23.wav";

  /**
   * 根据文件路径拷贝文件
   * @param src 源文件
   * @param destPath目标文件路径
   * @return boolean 成功true、失败false
   */
  public boolean copyFile(File src, String destPath) {
    boolean result = false;
    if ((src == null) || (destPath== null)) {
      return result;
    }
    File dest= new File(destPath + FileName);
    if (dest!= null && dest.exists()) {
      dest.delete(); // delete file
    }
    try {
      dest.createNewFile();
    } catch (IOException e) {
      e.printStackTrace();
    }

    FileChannel srcChannel = null;
    FileChannel dstChannel = null;

    try {
      srcChannel = new FileInputStream(src).getChannel();
      dstChannel = new FileOutputStream(dest).getChannel();
      srcChannel.transferTo(0, srcChannel.size(), dstChannel);
      result = true;
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return result;
    } catch (IOException e) {
      e.printStackTrace();
      return result;
    }
    try {
      srcChannel.close();
      dstChannel.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }

使用copyFile函数

private static final String AUDIO_FILE_PATH =
            Environment.getExternalStorageDirectory().getPath();

File file = new File(); // 此处为伪代码,实际为一个真实存在的文件,即你想复制的文件。

copyFile(file, AUDIO_FILE_PATH); 
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值