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

但是有时候我们需要的是获取文件的路径,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到外部存储需要申请权限
本文介绍了在Android Studio中如何创建并使用assets文件夹来存放资源文件,如json、字体等。当需要获取文件路径时,由于`file:///android_asset/`路径不可直接使用,建议通过复制资源到缓存目录来获取有效路径。提供了一个复制assets文件到缓存目录的代码示例,并强调了文件操作应在工作线程中进行以及外部存储权限的申请。
2752

被折叠的 条评论
为什么被折叠?



