写入JSONObject到JSONfile

时间:2017-11-19 16:31:53

标签: java android json bufferedreader

我有一个应用必须接受一个字符串,将其编码为JSONObject格式并将其写入SD中的JSON文件。除了写作部分外,这一切似乎都很好。我的MANIFEST中有<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />命令,这是我的代码

 btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          //  String lines[] =  importantemail.split("\\r?\\n");
          //  String firstLine = (lines[0]);
            //String secondLine = (lines[1]);
          //  Toast.makeText(SignificantEmailActivity.this,firstLine + secondLine,Toast.LENGTH_SHORT).show();;
            JSONObject jsonObject = makeJsonObject();
            try{
                Writer output = null;
                File file = new File(Environment.getExternalStorageDirectory()+ "importantemail.json");
                if (!file.exists()) {
                    file.mkdirs();
                }
                output = new BufferedWriter(new FileWriter(file));
                output.write(jsonObject.toString());
                output.close();
                Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
            finish();


        }
    });
    }
     public JSONObject makeJsonObject()
     {
         JSONObject object = new JSONObject();
         try {
             object.put("Message ID", id);
             object.put("Sender",accountStr);
             object.put("Subject",subj);
             object.put("E-mail:",importantemail);
         }catch (JSONException e)
         {
             e.printStackTrace();
         }
         return object;
     }

当我按下按钮时,我从Toast收到此消息 &#34;存储/模拟/ 0importantemail.json 许可被拒绝&#34; 不知道为什么会这样呢

2 个答案:

答案 0 :(得分:1)

经过测试,嗨替换几行,这将解决您的问题。

  JSONObject jsonObject = makeJsonObject();
    try{
        Writer output = null;
        File file = new File(Environment.getExternalStorageDirectory(), "importantemail.json");
        if(file.isDirectory()){
            file.delete();
        }
        if(!file.exists()){
            file.createNewFile();
        }
        output = new BufferedWriter(new FileWriter(file));
        output.write(jsonObject.toString());
        output.close();
        Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();

    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
    }
    finish();


}
public JSONObject makeJsonObject()
{
    JSONObject object = new JSONObject();
    try {
        object.put("Message ID", 5);
        object.put("Sender","test");
        object.put("Subject","test");
        object.put("E-mail:","test");
    }catch (JSONException e)
    {
        e.printStackTrace();
    }
    return object;
}

答案 1 :(得分:0)

在6.0或更高版本的android中,您必须提供运行时权限。检查this