我有一个应用程序,必须获取一个字符串,将其编码为 JSONObject 格式,然后将其写入 SD 中的 JSON 文件。除了写作部分之外,一切似乎都运行良好。我有<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我的 list 中的命令,这就是我的代码
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 收到此消息 “存储/模拟/0importantemail.json 没有权限” 不知道为什么会这样
最佳答案
经过测试,您好,替换几行即可解决您的问题。
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;
}
关于java - 将 JSON 对象写入 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47379171/