Writing and reading json data for Android internal storage

I have a json array received from php

[ { "name":"Daniel Bryan", "img":"pictures\/smallest\/dierdrepic.jpg", "username":"@dbryan", "user_id":"4" }, { "name":"Devil Hacker", "img":"pictures\/smallest\/belitapic.jpg", "username":"@dvHack", "user_id":"1" } ] 
  • I want to write this data to file_name.anyextension in my application data folder or anywhere in security.
  • Also read this data from file_name.anyextension and convert it to a valid json array , which can be further edited.

Can someone show me a way how can I do this?

+7
java json android arrays file
source share
1 answer
 private void writeToFile(String data) { try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE)); outputStreamWriter.write(data); outputStreamWriter.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } } private String readFromFile() { String ret = ""; try { InputStream inputStream = context.openFileInput("config.txt"); if ( inputStream != null ) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String receiveString = ""; StringBuilder stringBuilder = new StringBuilder(); while ( (receiveString = bufferedReader.readLine()) != null ) { stringBuilder.append(receiveString); } inputStream.close(); ret = stringBuilder.toString(); } } catch (FileNotFoundException e) { Log.e("login activity", "File not found: " + e.toString()); } catch (IOException e) { Log.e("login activity", "Can not read file: " + e.toString()); } return ret; } 

When a read line from a file converts it to JsonObject or JsonArray

 JSONArray jarray = new JSONArray(str); 
+15
source share

All Articles