Java 如何将JSON数据写入外部存储器
我想将Arraylist写入外部存储器。该文件应为Json格式 文件名=notes.jsonJava 如何将JSON数据写入外部存储器,java,android,Java,Android,我想将Arraylist写入外部存储器。该文件应为Json格式 文件名=notes.json private boolean isExternalStorageWritable(){ if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){ System.out.println("Storage is writeable"); return true;
private boolean isExternalStorageWritable(){
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
System.out.println("Storage is writeable");
return true;
}
else{
return false;
}
}
private void wirteFile(){
if(isExternalStorageWritable()){
File textFile = new File(Environment.getExternalStorageDirectory(), FILE_NAME);
try{
FileOutputStream fos = new FileOutputStream(textFile);
fos.write(arrlist.toString().getBytes());
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
您必须首先将ArrayList转换为JSONObject。然后,只需对创建的对象调用
toString()
方法
if (isExternalStorageWritable()) {
File file = new File(Environment.getExternalStorageDirectory(), FILE_NAME);
JSONObject jsonObject = fromArrayList(arrayList); // you have to develop it
try {
Writer output = new BufferedWriter(new FileWriter(file));
output.write(jsonObject.toString());
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
使用FileOutputStream
try {
FileOutputStream output = new FileOutputStream(file);
output.write(jsonObject.toString().getBytes());
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
我给您一个将数据转换为JSONObject的示例
public class ListItem {
private int id;
private String name;
public ListItem(int id, String name) {
this.id = id;
this.name = name;
}
public JSONObject toJSONObject() {
JSONObject object = new JSONObject();
try {
object.put("Id", id);
object.put("Name", name);
} catch (JSONException e) {
trace("JSONException: "+e.getMessage());
}
return object;
}
}
然后呢,
public JSONObject fromArrayList(ArrayList<ListItem> arrayList) {
JSONObject object = new JSONObject();
JSONArray jsonArray = new JSONArray();
for (int i=0; i < arrayList.size(); i++) {
jsonArray.put(arrayList.get(i).toJSONObject());
}
object.put("result", jsonArray);
return object;
}
来自ArrayList的公共JSONObject(ArrayList ArrayList){
JSONObject对象=新的JSONObject();
JSONArray JSONArray=新的JSONArray();
对于(int i=0;itoJSON()的方法来转换JSON对象中的数据。然后,要转换ArrayList,只需对所有项进行迭代即可使用FileOutputStream写入ExternalStorage,它的外观如何请参见我编辑的答案。希望它能帮助你。我不能做JSONObject put=object.put(arraylist);