转载请注明出处:http://blog.csdn.net/krislight

项目中遇到备份与还原App数据的需求,需要把DB数据备份到一个XML文件中,然后保存到SD卡上,还原的时候直接从XML文件解析数据进行insert DB动作。

现总结下实现方法,定义一个工具类

/**
* from sqlite to xml
*
* @author Kris
*/
public class DatabaseLog { // back up dir
private String mDestXmlFileDir = "/psmd/appName/backup/";
private SQLiteDatabase mDb;
private Exporter mExporter; /**
* @param db database
*/
public DatabaseLog(SQLiteDatabase db,String fileName) {
mDb = db;
try {
Calendar cal = Calendar.getInstance();
//use date+time as filename e.g. 2013_04_03_13_23_49.backup
if(TextUtils.isEmpty(fileName)){
fileName = cal.get(Calendar.YEAR)+"_"+cal.get(Calendar.MONTH)+"_"+cal.get(Calendar.DAY_OF_MONTH)+"_"
+cal.get(Calendar.HOUR_OF_DAY)+"_"+cal.get(Calendar.MINUTE)+"_"+cal.get(Calendar.MINUTE);
}
fileName += ".backup";
File sdDir = Environment.getExternalStorageDirectory();
File theDir = new File(sdDir, mDestXmlFileDir);
if (!theDir.exists()) {
theDir.mkdirs();
}
File picFile = new File(theDir, fileName);
picFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(picFile);
BufferedOutputStream bos = new BufferedOutputStream(fOut);
mExporter = new Exporter(bos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* export
*/
public void exportData() {
try {
//1.先查找icon存放的目录复制所有图片到備份目錄下面
// 还原的时候检查这个栏位对应的文件是否存在,不存在则用backup下面的文件路径,然后update db
mExporter.startDbExport(C_9510_PSMD_DBAdapter.DATABASE_NAME);
//TODO export database and table
exportTable("C_EVNT_EVNT");
exportTable("C_EVNT_PSON");
exportTable("R_EVNT_SEND");
exportTable("R_EVNT_RECV");
exportTable("C_TMPL_TYPE");
exportTable("C_TMPL_EVDS");
mExporter.endDbExport();
mExporter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
转载请注明出处:http://blog.csdn.net/krislight 

	/**
*
* @param tableName
* @throws IOException
*/
private void exportTable(String tableName) throws IOException {
mExporter.startTable(tableName);
// get everything from the table
String sql = "select * from " + tableName;
Cursor cur = mDb.rawQuery(sql, new String[0]);
int numcols = cur.getColumnCount();
cur.moveToFirst();
// move through the table, creating rows // and adding each column with
// name and value
// to the row
while (cur.getPosition() < cur.getCount()) {
mExporter.startRow();
String name;
String val;
for (int idx = 0; idx < numcols; idx++) {
name = cur.getColumnName(idx);
val = cur.getString(idx);
mExporter.addColumn(name, val);
}
mExporter.endRow();
cur.moveToNext();
}
cur.close();
mExporter.endTable();
} public class Exporter {
private static final String OPEN_XML_STANZA = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
private static final String CLOSING_WITH_TICK = "'>";
private static final String START_DB = "<export-database name='";
private static final String END_DB = "</export-database>";
private static final String START_TABLE = "<table name='";
private static final String END_TABLE = "</table>";
private static final String START_ROW = "<row>";
private static final String END_ROW = "</row>";
private static final String START_COL = "<col name='";
private static final String END_COL = "</col>";
private BufferedOutputStream mbufferos; public String getFileName() {
return ""; } public Exporter(BufferedOutputStream bos) {
mbufferos = bos;
} public void close() throws IOException {
if (mbufferos != null) {
mbufferos.close();
}
} public void startDbExport(String dbName) throws IOException {
StringBuffer sb = new StringBuffer();
sb.append(OPEN_XML_STANZA).append(START_DB).append(dbName).append(CLOSING_WITH_TICK);
mbufferos.write(sb.toString().getBytes());
} public void endDbExport() throws IOException {
mbufferos.write(END_DB.getBytes());
} public void startTable(String tableName) throws IOException {
StringBuffer sb = new StringBuffer();
sb.append(START_TABLE).append(tableName).append(CLOSING_WITH_TICK);
mbufferos.write(sb.toString().getBytes());
} public void endTable() throws IOException {
mbufferos.write(END_TABLE.getBytes());
} public void startRow() throws IOException {
mbufferos.write(START_ROW.getBytes());
} public void endRow() throws IOException {
mbufferos.write(END_ROW.getBytes());
} public void addColumn(String name, String val) throws IOException {
StringBuffer sb = new StringBuffer();
sb.append(START_COL).append(name).append(CLOSING_WITH_TICK).append(val).append(END_COL);
mbufferos.write(sb.toString().getBytes());
}
}
}

備份Sqlite DB到XML文件:的更多相关文章

  1. XML文件编码问题

    这两天的过程中的一个项目,以解决编码格式ANSI的xml当文件.我遇到了一些问题.下面的例子现在将总结分析过程. 通过win7记事本或notepad++创建一个xml文件test_source: &l ...

  2. Java眼中的XML文件写入

    创建DOM方式生成XML文档 DOMTest package com.imooc.domtest.test; import java.io.File; import java.io.IOExcepti ...

  3. 无废话Android之android下junit测试框架配置、保存文件到手机内存、android下文件访问的权限、保存文件到SD卡、获取SD卡大小、使用SharedPreferences进行数据存储、使用Pull解析器操作XML文件、android下操作sqlite数据库和事务(2)

    1.android下junit测试框架配置 单元测试需要在手机中进行安装测试 (1).在清单文件中manifest节点下配置如下节点 <instrumentation android:name= ...

  4. android开发 解析服务器端xml文件数据存储到android客户端SQLite数据库

    以下面xml文件为例对其解析(假设此xml就在服务器端Server项目下的servlet包下的MenuServlet文件的输出流中): <?xml version="1.0" ...

  5. Android开发 ---SQLite数据库,lock文件,结果集游标,适配器,安全退出,给连接设置下划线,编辑器,投影,ContentValues存储,DbHelper,activity栈

    目录截图: 1.activity_main.xml 主界面效果: <?xml version="1.0" encoding="utf-8"?> &l ...

  6. android读取xml文件来实现省份,城市,区的选择

    本博客如需转载.请注明出处. ------------------------------------------------------------------------------------- ...

  7. 流暢的pyhton4---數據庫備份

    一.linux數據庫備份腳本 1.数据库备份,命令如下: ./pg_dump -h localhost -p 5432 -U postgres -W -F c -b -v -f "/opt/ ...

  8. java读取xml文件

    public ArrayList getMessage(){ String xmlFileName = null; List list = new ArrayList(); MessageBean m ...

  9. java解析XML文件

    dom4j是一个Java的XML API,类似于jdom,用来读写XML文件的.dom4j是一个非常非常优秀的Java XML API,具有性能优异.功能强大和极端易用使用的特点,同时它也是一个开放源 ...

随机推荐

  1. Asp.net上传出现“超过了最大请求长度”的问题解决方法

    在开发ASP.NET网站后台管理系统时,我们可能会遇到这样的问题:上传大于4M的文件时,会提示错误:错误信息如下: 1.异常详细信息:超过了最大请求长度. 2.引发异常的方法:Byte[] GetEn ...

  2. HDU-1060(简单数学)

    Leftmost Digit Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) P ...

  3. order by跟group by 跟having(2)

  4. 学习笔记6_Java_day11_JSP_基础和入门(1、2)

    主要内容:1. JSP基础2. Cookie3. HttpSession ================================ JSP基础 1. jsp的作用: * Servlet: &g ...

  5. 根据id设置、获取元素的文本和value

    /** * 根据id获取元素文本 * @param {String} id|元素id * return {Integer || String} text */function getText(id){ ...

  6. Windwos平台上ffmpeg解码音频并且保存到wav文件中

    先附上代码,测试通过 #include <stdio.h> #include <math.h> #include "libavutil/avstring.h" ...

  7. 九度OJ 1373 整数中1出现的次数(从1到n整数中1出现的次数)

    题目地址:http://ac.jobdu.com/problem.php?pid=1373 题目描述: 亲们!!我们的外国友人YZ这几天总是睡不好,初中奥数里有一个题目一直困扰着他,特此他向JOBDU ...

  8. (转)IOS开发之——绘图(CGContext)

    周刊 更多 登录   IOS开发之——绘图(CGContext) 时间 2014-04-21 09:17:43 CSDN博客 原文  http://blog.csdn.net/zhenyu521131 ...

  9. linux-信号。

    信号 信号是在软件层次上对中断机制的一种模拟,在原理上,一个进程收到一个信号与处理器收到一个中断请求可以说是一样的. 信号是异步的,一个进程不必通过任何操作来等待信号的到达,事实上,进程也不知道信号到 ...

  10. javascript 学习笔记之模块化编程

    题外: 进行web开发3年多了,javascript(后称js)用的也比较多,但是大部分都局限于函数的层次,有些公共的js函数可重用性不好,造成了程序的大量冗余,可读性差(虽然一直保留着注释的习惯,但 ...