以备份短信为例,假设已经获取到了手机系统里所有短信的信息。
第一种方式: -----不推荐
1.new 一个 StringBuilder容器
3.指定要存储的路径,将容器中的数据以IO流的形式输出到指定位置。public void backSms1(View view){ //假设我们已经获得了所有的短信 StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); sb.append("<smss>"); for (SmsInfo info : smsInfos) { sb.append("<sms>"); sb.append("<address>"); sb.append(info.getAddress()); sb.append("</address>"); sb.append("<type>"); sb.append(info.getAddress()); sb.append("</type>"); sb.append("<body>"); sb.append(info.getAddress()); sb.append("</body>"); sb.append("<date>"); sb.append(info.getAddress()); sb.append("</date>"); sb.append("</sms>"); } sb.append("</smss>"); try { File file = new File(Environment.getExternalStorageDirectory(),"backup.xml"); FileOutputStream fos = new FileOutputStream(file); fos.write(sb.toString().getBytes()); fos.close(); Toast.makeText(this,"备份成功",Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(this,"备份失败",Toast.LENGTH_SHORT).show(); e.printStackTrace(); } }
第二种方式:
1.获取xml文件的序列化器
2.指定xml文件的路径、编码方式
public void backSms2(View view){ try{ XmlSerializer serializer = Xml.newSerializer(); File file = new File(Environment.getExternalStorageDirectory(),"backup2.xml"); FileOutputStream fos = new FileOutputStream(file); //初始化序列号器 指定xml数据写入到哪个文件 并且指定文件的编码方式 serializer.setOutput(fos,"utf-8"); serializer.startDocument("utf-8",true); serializer.startTag(null,"smss"); for(SmsInfo info : smsInfos){ serializer.startTag(null,"sms"); serializer.attribute(null,"id",info.getId()+""); serializer.startTag(null,"body"); serializer.text(info.getBody()); serializer.endTag(null,"body"); serializer.startTag(null,"address"); serializer.text(info.getAddress()); serializer.endTag(null,"address"); serializer.startTag(null,"type"); serializer.text(info.getType()+""); serializer.endTag(null,"type"); serializer.startTag(null,"date"); serializer.text(info.getDate()+""); serializer.endTag(null,"date"); serializer.endTag(null,"sms"); } serializer.endTag(null,"smss"); serializer.endDocument(); fos.close(); Toast.makeText(this,Toast.LENGTH_SHORT).show(); }catch(Exception e){ e.printStackTrace(); Toast.makeText(this,Toast.LENGTH_SHORT).show(); } }原文链接:https://www.f2er.com/xml/297309.html