为了账号安全,请及时绑定邮箱和手机立即绑定

Android获取assets文件路径

标签:
Android

我们有时候需要放置一些资源例如json,字体,视频,音频以及其他格式的资源。为了保证这些资源不被编译,以便于我们在代码中可以正常使用,我们可以放置到assets文件夹下。这个文件夹在哪呢?看下图,Android Studio新建一个项目是没有这个文件夹的,你可以在需要的时候新建这个文件夹。

这里写图片描述

我们如何使用这些文件呢?如何使用下面这一篇博客说的很详细,加载网页读取文本图片播放视频等等
https://blog.csdn.net/greathfs/article/details/52123984

但是有时候我们需要的是获取文件的路径,file:///android_asset/data.xx貌似并不是可以使用的路径,这时候可以曲线救国,我们先把文件copy到缓存文件夹中,然后就可以拿到路径了

/**
 * 将asset文件写入缓存
 */private boolean copyAssetAndWrite(String fileName){    try {
        File cacheDir=getCacheDir();        if (!cacheDir.exists()){
            cacheDir.mkdirs();
        }
        File outFile =new File(cacheDir,fileName);        if (!outFile.exists()){            boolean res=outFile.createNewFile();            if (!res){                return false;
            }
        }else {            if (outFile.length()>10){//表示已经写入一次
                return true;
            }
        }
        InputStream is=getAssets().open(fileName);
        FileOutputStream fos = new FileOutputStream(outFile);        byte[] buffer = new byte[1024];        int byteCount;        while ((byteCount = is.read(buffer)) != -1) {
            fos.write(buffer, 0, byteCount);
        }
        fos.flush();
        is.close();
        fos.close();        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }    return false;
}

拿的时候如何拿呢?

File dataFile=new File(getCacheDir(),fileName);Log.d(TAG,"filePath:" + dataFile.getAbsolutePath());

注意点:
1,Android中文件copy操作要放置工作线程中避免卡顿和anr
2,如果你特殊需要,把文件copy到外部存储需要申请权限

原文出处

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消