600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > android读取assets中的txt文件路径 Android获取assets文件路径

android读取assets中的txt文件路径 Android获取assets文件路径

时间:2018-12-21 23:21:00

相关推荐

android读取assets中的txt文件路径 Android获取assets文件路径

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。