【问题标题】:How to write to a json file which is stored in asset folder?如何写入存储在资产文件夹中的 json 文件?
【发布时间】:2018-04-02 09:57:11
【问题描述】:

我的应用程序的资产文件夹中有一个 config.json 文件。现在的情况是,我将从服务器中提取 JSON 内容,并更新(覆盖)存储在资产文件夹中的 config.json 文件。我怎样才能做到这一点?这是 JSON 的示例:

{
    "id": 1,
    "name": "A green door",
    "price": 12.50,
    "tags": ["home", "green"]
}

我能够从资产文件夹中读取文件。但是如何写入那个文件呢?:

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;
}

【问题讨论】:

  • 您无法写入资产文件夹。它是只读的。
  • 无法在同一个应用程序中修改 APK 内容。因此,您不能写入资产文件
  • 还有其他意见吗?如何写入本地文件? @ישואוהבאותך
  • 您可以将文件保存到您的应用文件夹中。
  • 您可以轻松写入本地文件。

标签: android json


【解决方案1】:

您不能写入资产文件夹。因为它是一个只读文件夹。相反,您需要将文件保存到您的应用程序文件夹中。每当您想使用配置时,请检查该文件是否存在于您的应用文件夹中。如果存在,使用它,如果没有,使用默认的。

例如,当你得到 config.json 时,保存文件:

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();
}

然后,当你想使用时,阅读它:

File file = new File(context.getFilesDir(), "config.json");

String config = "";
if(file.exists()) {
  // use the config.
} else {
  // use the config from asset.
}

Save Files on Device Storage 阅读更多信息以保存文件。

【讨论】:

  • 太棒了。谢谢您的帮助。我明白了
【解决方案2】:

无论我们在 assets 文件夹中保存什么文件,都不能在运行时进行修改。在 APK 中,文件是只读的。我们既不能删除也不能在这个目录中创建任何文件。

您可以将新的 JSON 写入文件(例如,getFilesDir()) As this answers suggests

【讨论】:

    【解决方案3】:

    您不能将数据写入asset/Raw 文件夹,因为它是打包的(.apk)并且大小不可扩展。 check here

    【讨论】:

    • 还有其他方法可以实现吗? @ss_
    • 您可以使用本地存储,如内部存储、外部存储、共享首选项、数据库
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    相关资源
    最近更新 更多