First, read the file under the assets file 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); } }
Calling Methods
Readassetfile (Testactivity.this, "Product.json");
Second, read the Res/raw folder file 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) {//third bit is | The string is a country 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); }//Province or State 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 (Countri Es.size ()-1). GetStates (). Add (state); }}//City 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 (); } }
Android Development Step by Step 54: Read the file under the Assets,raw folder