Android获取assets文件路径

我们有时候需要放置一些资源例如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到外部存储需要申请权限

猜你喜欢

转载自blog.csdn.net/dreamsever/article/details/80468464