asset裡面gson檔案讀取方法
阿新 • • 發佈:2019-01-09
1.讀取asset目錄下json檔案並轉成bean
InputStream is=getResources().getAssets().open("xxxx.json");
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte[] bytes=new byte[1024];
int length;
while((length=is.read(bytes))!=-1){
baos.write(bytes,0,length);
}
return new Gson().<ArrayList<SubTab>>fromJson(new String(baos.toByteArray(),"UTF-8"),new TypeToken<ArrayList<SubTab>>(){}.getType());
2.讀取本地檔案並轉換成bean
byte[] bytes=new byte[1024]; int length; ByteArrayOutputStream baos=new ByteArrayOutputStream(); InputStream is; File file=getContext().getFileStreamPath("xxx.json"); if (file.exists()){ is=getContext().openFileInput("xxx.json"); }else { is=getResources().getAssets().open("xxx.json"); } while ((length=is.read(bytes))!=-1){ baos.write(bytes,0,length); } return new Gson().<ArrayList<SubTab>>fromJson(new String(baos.toByteArray(),"UTF-8"),new TypeToken<ArrayList<SubTab>>(){}.getType());
3.將檔案寫在本地檔案中
String json = new Gson().toJson(activeTabs); try { FileOutputStream fos = getContext().openFileOutput("xxx.json", Context.MODE_PRIVATE); fos.write(json.getBytes("UTF-8")); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); }