I wanted to store JSONObject in a file.
For the purpose I converted the Object to string and then stored it in a file.
The code that I used is :
String card_string = card_object.toString();
//card_object is the JSONObject that I want to store.
f = new File("/sdcard/myfolder/card3.Xcard");
//file 'f' is the file to which I want to store it.
FileWriter fw = new FileWriter(f);
fw.write(card_string);
fw.close();
The code works as I want it. Now I want to retrieve that object back from the File.
How should I do it? I am getting confused on what to use to read the file ?
an InputStream or a FileReader or BufferedReader or what. I am new to JAVA / android development.
please help. A detailed explanation in simple words regarding what I/O functions to be used in different scenarios (like this) is welcome. I have had a look at documentation but your suggestions are welcome.
You can use this code to read file.
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(
openFileInput("jsonfile")));
String line;
StringBuffer content = new StringBuffer();
char[] buffer = new char[1024];
int num;
while ((num = input.read(buffer)) > 0) {
content.append(buffer, 0, num);
}
JSONObject jsonObject = new JSONObject(content.toString());
}catch (IOException e) {...}
Then you can use your jsonObject:
To get a specific string from JSON Object
String name = jsonObject.getString("name");
To get a specific int
int id = jsonObject.getInt("id");
To get a specific array
JSONArray jArray = jsonObject.getJSONArray("listMessages");
To get the items from the array
JSONObject msg = jArray.getJSONObject(1);
int id_message = msg.getInt("id_message");
Use could use a BufferedReader and FileReader:
File file = new File("/sdcard/myfolder/card3.Xcard");
StringBuilder text = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
// do exception handling
} finally {
try { br.close(); } catch (Exception e) { }
}
In addition I'd propose that you use Environment.getExternalStorageDirectory(); for building up the path. That's less device specific.
Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With