源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android编程读取Assets所有文件(遍历每一个文件夹)并存入sdcard的方法

  • 时间:2020-02-18 09:18 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android编程读取Assets所有文件(遍历每一个文件夹)并存入sdcard的方法
本文实例讲述了Android编程读取Assets所有文件(遍历每一个文件夹)并存入sdcard的方法。分享给大家供大家参考,具体如下:
private void CopyAssets(String assetDir, String dir) {
    String[] files;
    try {
      // 获得Assets一共有几多文件
      files = this.getResources().getAssets().list(assetDir);
    } catch (IOException e1) {
      return;
    }
    File mWorkingPath = new File(dir);
    // 如果文件路径不存在
    if (!mWorkingPath.exists()) {
      // 创建文件夹
      if (!mWorkingPath.mkdirs()) {
        // 文件夹创建不成功时调用
      }
    }
    for (int i = 0; i < files.length; i++) {
      try {
        // 获得每个文件的名字
        String fileName = files[i];
        // 根据路径判断是文件夹还是文件
        if (!fileName.contains(".")) {
          if (0 == assetDir.length()) {
            CopyAssets(fileName, dir + fileName + "/");
          } else {
            CopyAssets(assetDir + "/" + fileName, dir + "/"
                + fileName + "/");
          }
          continue;
        }
        File outFile = new File(mWorkingPath, fileName);
        if (outFile.exists())
          outFile.delete();
        InputStream in = null;
        if (0 != assetDir.length())
          in = getAssets().open(assetDir + "/" + fileName);
        else
          in = getAssets().open(fileName);
        OutputStream out = new FileOutputStream(outFile);
        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
          out.write(buf, 0, len);
        }
        in.close();
        out.close();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }
      catch (IOException e) {
        e.printStackTrace();
      }
    }
}

更多关于Android相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/410.htm]Android开发入门与进阶教程[/url]》、《[url=http://www.1sucai.cn/Special/402.htm]Android数据库操作技巧总结[/url]》及《[url=http://www.1sucai.cn/Special/124.htm]Android控件用法总结[/url]》 希望本文所述对大家Android程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部