一、读取assets文件下文件products.json
public String readAssetFile(Context c, String file) { Elapsed profiler = new Elapsed(); BufferedReader bufReader = null; try { InputStreamReader inputReader = new InputStreamReader(c.getResources().getAssets().open(file)); bufReader = new BufferedReader(inputReader); StringBuilder sb = new StringBuilder(); String line = null; while ((line = bufReader.readLine()) != null) sb.append(line); return sb.toString(); } catch (Exception e) { LogUtil.i(TAG, "FileUtils.getFromAssets Exception:" + file); return ""; } catch (OutOfMemoryError e) { LogUtil.i(TAG, "FileUtils.getFromAssets OutOfMemoryError:" + file); return ""; } finally { CommonUtils.close(bufReader); profiler.log("FileUtils.getFromAssets:" + file); } }
调用方法
readAssetFile(testActivity.this,"product.json");
二、读取res/raw文件夹下文件cities.txt
private void loadAddressDataNew() { countries = new ArrayList<Country>(); InputStreamReader inputStreamReader = null; try { inputStreamReader = new InputStreamReader(getResources().openRawResource(R.raw.cities), "utf8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } BufferedReader reader = new BufferedReader(inputStreamReader); String line; try { while ((line = reader.readLine()) != null) { //第三位为|则该string为国家 CN|China if (line.substring(2, 3).equals("|")) { Country country = new Country(); country.setCountryId(line.substring(0, 2)); country.setCountryName(line.substring(3)); countries.add(country); } //省 or 州 CN_Anhui|Anhui if (line.substring(0, line.lastIndexOf("|")).lastIndexOf("_") == 2) { State state = new State(); state.setStateName(line.substring(line.lastIndexOf("|") + 1)); if (line.indexOf(countries.get(countries.size() - 1).getCountryId()) != -1) { countries.get(countries.size() - 1).getStates().add(state); } } //城市CN_Anhui_Anqing|Anqing if (line.substring(0, line.lastIndexOf("|")).lastIndexOf("_") > 2) { City city = new City(); city.setCityName(line.substring(line.lastIndexOf("|") + 1)); int stateIndex = countries.get(countries.size() - 1).getStates().size() - 1; if (line.indexOf(countries.get(countries.size() - 1).getStates().get(stateIndex).getStateName()) != -1) { countries.get(countries.size() - 1).getStates().get(stateIndex).getCities().add(city); } } // } } } catch (IOException e) { e.printStackTrace(); } }
时间: 2024-10-21 20:22:59