Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write to a json file which is stored in asset folder?

Tags:

json

android

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;
}
like image 531
sagar suri Avatar asked Dec 23 '22 08:12

sagar suri


2 Answers

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.

like image 184
ישו אוהב אותך Avatar answered Dec 25 '22 20:12

ישו אוהב אותך


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

like image 31
MuhammadAliJr Avatar answered Dec 25 '22 20:12

MuhammadAliJr