在项目开发的过程中,会遇到很多需要读取本地文件的内容的需求,如读取所有的银行,和读取所有的城市名等等!
如下示意图:
**第一步;**在main文件下,新建assets文件,并将资源文件bankresource.txt文件导入,如下
{"ICBC":"中国工商银行","ABC":"中国农业银行","CCB":"中国建设银行","CMB":"招商银行","CEB":"中国光大银行","CIB":"兴业银行","SPDB":"上海浦东发展银行","COMM":"交通银行","CITIC":"中信银行","HXBANK":"华夏银行","BOC":"中国银行","CMBC":"中国民生银行","PSBC":"中国邮政储蓄银行","GCB":"广州银行","SRCB":"深圳农村商业银行","SPABANK":"平安银行"}
第二步:自定义getFromAssets方法,将对象装换成字符串
//已流的方式读取
public String getFromAssets(String fileName) {
StringBuilder stringBuilder = new StringBuilder();
try {
InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open(fileName));
BufferedReader bufReader = new BufferedReader(inputReader);
String line = "";
while ((line = bufReader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
第三步:将读取出来的String中分离出来key和value
//读取assets里面文件的数据
String content = getFromAssets(FILE_NAME);
if (TextUtils.isEmpty(content)) {
return;
}
//对象集合
mBankInfoList = new ArrayList<BankInfo>();
try {
JSONObject object = new JSONObject(content);
Iterator<?> iterator = object.keys();
//循环迭代器中的key值
while (iterator.hasNext()) {
//code为解析出来的key值,如ICBC
String code = iterator.next().toString();
if (code != null) {
//name为根据code解析出来的value值,如中国工商银行
String name = object.getString(code);
Log.e("打印出来", code + "================");
Log.e("打印出来", name + "------------------");
//BankInfo为Bean对象
mBankInfoList.add(new BankInfo(code, name, false));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//适配器
mBankSelectedAdapter = new BankSelectedAdapter(this, mBankInfoList);
另外:获取assets下文件的路径:
**方法一:仅仅只针对assets下的单一文件,如html等,例如apk格式的就不行
** String path = “file:///android_asset/icon_wm.png”;
**方法二:**通过流的方式去处理
/**
* 将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());
以上,即可实现读取assets中文件