一尘不染

将json数据写入和读取到内部存储Android

json

我从php收到一个json数组

[  
   {  
      "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"
   }
]
  • 我想要的是将此数据 写入file_name.anyextension我的应用程序数据文件夹中或安全的任何位置。
  • 还要从中读取此数据file_name.anyextension并将其转换为json array可以进一步编辑的有效数据。

谁能告诉我一种方法我怎么可能做这件事?


阅读 440

收藏
2020-07-27

共1个答案

一尘不染

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

从文件中读取字符串时,将其转换为JsonObject或JsonArray

JSONArray jarray = new JSONArray(str);
2020-07-27