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

2022-09-03 12:13:19

我有一个从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.anyextensionjson array

谁能给我一个办法,我怎么可能到这个东西?


答案 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);

答案 2

Morteza Soleimani的更正答案:

public static String readFromFile(String path) {
    String ret = "";
    try {
        InputStream inputStream = new FileInputStream(new File(path));

        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("FileToJson", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("FileToJson", "Can not read file: " + e.toString());
    }
    return ret;
}