web-dev-qa-db-ja.com

内部ストレージへのjsonデータの書き込みと読み取りandroid

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"
   }
]
  • 私が欲しいのはwriteアプリのデータフォルダーまたは安全な場所のfile_name.anyextensionにあるこのデータです。
  • また、このデータをfile_name.anyextensionから読み取り、さらに編集できる有効なjson arrayに変換します。

誰かが私にこのことをどうやってできるのか私に方法を示すことができますか?

11
Slim Shady
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);
21
Saeid N.

読むためのモルテザソレイマニの正しい答え:

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