如何在Android studio中读取文件并将其存储到json数组中

时间:2017-12-12 17:56:33

标签: java android json

以下是Android Studio中的代码,我创建了一个json对象,其中包含一个用户的用户名和密码,并将其存储到json数组(只是为了拥有更多用户)。实际上是在存储之前将其转换为String。 那么如何读取并将其存储回包含json对象的json数组?

这是代码

public void storeJson() {

            jobj = new JSONObject();

            try {
                jobj.put("username",usern);
                jobj.put("password",passwd);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            jarray = new JSONArray();
            jarray.put(jobj);
            String str = jarray.toString();

            try {
                fileOutputStream =  openFileOutput(passwordFile, 0);
                fileWriter = new OutputStreamWriter(fileOutputStream);

                try {
                    fileWriter.write(str);
                    fileWriter.flush();
                    fileWriter.close();
                    Toast.makeText(getApplicationContext(), "File Written", Toast.LENGTH_LONG).show();
                    username.setText("");
                    password.setText("");

                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), "Write Error", Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

}

0 个答案:

没有答案