手动生成xml文件——模拟短信备份
xml生成格式:
|
一、手动编码代码生成xml文件 /**
* 1、手动备份短信信息到一个xml文件中去
* @param view
*/
public void click1(View view) {
try {
// 1、用一个FileOutputStream关联文件输出
String externalStorageState = Environment.getExternalStorageState();
Log.i(TAG, "sdcard状态:" + externalStorageState);
File file = new File(Environment.getExternalStorageDirectory(),"smsinfo.xml");
FileOutputStream fos = new FileOutputStream(file);
// 2、用一个StringBuilder来保存数据
StringBuilder sbBuilder = new StringBuilder();
sbBuilder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sbBuilder.append("<smss>");
for (SmsInfo smsInfo : listsSmsInfos) {
// 3、然后将数据写到一个xml文件中去
sbBuilder.append("<sms>");
sbBuilder.append("<body>");
sbBuilder.append("</body>" + smsInfo.getBody());// 这里有非法字符,写成的xml文件不能正常打开,需要手动对特殊进行转义
sbBuilder.append("</body>");
sbBuilder.append("<address>");
sbBuilder.append(smsInfo.getAddress());
sbBuilder.append("</address>");
sbBuilder.append("<date>");
sbBuilder.append(String.valueOf(smsInfo.getDate()));
sbBuilder.append("</date>");
sbBuilder.append("</sms>");
}
sbBuilder.append("</smss>");
fos.write(sbBuilder.toString().getBytes());
// 4、关闭资源
fos.close();
Toast.makeText(this, "备份短信到xml成功!", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "备份短信到xml失败!", 0).show();
return;
}
} |
二、使用xSerializer生成xml文件 /**
* 2、使用xSerializer生成xml文件
* 可以解决特殊字符的问题,会进行自动转义的操作
* @param view
*/
public void click(View view) {
Log.i(TAG, "开始备份了。。。");
try {
// 1,初始化一个xml文件的序列化器
XmlSerializer xSerializer = Xml.newSerializer();
// 2.初始化序列器参数
File file = new File(Environment.getExternalStorageDirectory(),"smsinfo.xml");
FileOutputStream fos = new FileOutputStream(file);
xSerializer.setOutput(fos, "utf-8");
// 3.开始写xml文件.
xSerializer.startDocument("utf-8", true);
xSerializer.startTag(null, "smss");
for (SmsInfo smsInfo : listsSmsInfos) {
xSerializer.startTag(null, "sms");
xSerializer.startTag(null, "body");
xSerializer.text("</body>" + smsInfo.getBody());
xSerializer.endTag(null, "body");
xSerializer.startTag(null, "address");
xSerializer.text(smsInfo.getAddress());
xSerializer.endTag(null, "address");
xSerializer.startTag(null, "date");
xSerializer.text(String.valueOf(smsInfo.getDate()));
xSerializer.endTag(null, "date");
xSerializer.endTag(null, "sms");
}
xSerializer.endTag(null, "smss");
xSerializer.endDocument();
fos.close();
Toast.makeText(this, "备份短信到xml成功!", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "备份短信到xml失败!", 0).show();
}
} |