I have a config.json file in the asset folder in my application. Now the scenario is, I will pull a JSON content from server and will update(override) the config.json file stored in asset folder. How can I achieve this? Here is sample of JSON:
{
"id": 1,
"name": "A green door",
"price": 12.50,
"tags": ["home", "green"]
}
I am able to read the file from the asset folder. But how to write in that file?:
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("config.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
You can't write to asset folder. because it's a read-only folder. Instead, you need to save the file to your app folder. Whenever you want to use the config, check if the file is existed in your app folder. if it's exist, use it, if not, use the default one.
For example, when you get the config.json, save the file:
String filename = "config.json";
String fileContents = "Your config content..";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(fileContents.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Then, whenever you want to use, read it:
File file = new File(context.getFilesDir(), "config.json");
String config = "";
if(file.exists()) {
// use the config.
} else {
// use the config from asset.
}
Read more at Save Files on Device Storage for saving the file.
Whatever the files we keep in assets folder, it can not be modified at run time. Within an APK, files are read-only. Neither we can delete nor we can create any files within this directory.
What you can do is write your new JSON to a file (e.g., getFilesDir()) As this answers suggests
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