我们有时候需要放置一些资源例如json,字体,视频,音频以及其他格式的资源。为了保证这些资源不被编译,以便于我们在代码中可以正常使用,我们可以放置到assets文件夹下。这个文件夹在哪呢?看下图,Android Studio新建一个项目是没有这个文件夹的,你可以在需要的时候新建这个文件夹。
/**
*将asset文件写入缓存
*/privatebooleancopyAssetAndWrite(StringfileName){try{
FilecacheDir=getCacheDir();if(!cacheDir.exists()){
cacheDir.mkdirs();
}
FileoutFile=newFile(cacheDir,fileName);if(!outFile.exists()){booleanres=outFile.createNewFile();if(!res){returnfalse;
}
}else{if(outFile.length()>10){//表示已经写入一次
returntrue;
}
}
InputStreamis=getAssets().open(fileName);
FileOutputStreamfos=newFileOutputStream(outFile);byte[]buffer=newbyte[1024];intbyteCount;while((byteCount=is.read(buffer))!=-1){
fos.write(buffer,0,byteCount);
}
fos.flush();
is.close();
fos.close();returntrue;
}catch(IOExceptione){
e.printStackTrace();
}returnfalse;
}
拿的时候如何拿呢?FiledataFile=newFile(getCacheDir(),fileName);Log.d(TAG,"filePath:"+dataFile.getAbsolutePath());
注意点:
1,Android中文件copy操作要放置工作线程中避免卡顿和anr
2,如果你特殊需要,把文件copy到外部存储需要申请权限