Android Sqlite 数据初始化

android系统下每个程序的数据存放在 /data/data/(package name)/ 目录下,数据库则是在/dababases/目录下..
所以,你只要用FileInputStream读取原数据库,再用FileOutputStream把读取到的东西写入到那个目录就可以了..

操作方法:1. 把原数据库包括在项目源码的 res/raw 目录下.
2.创建一个类来控制database..如下:

 

public class DatabaseManager{
        private final int BUFFER_SIZE = 400000;
        public static final String DB_NAME = "myDatabase.db"; //保存的数据库文件名
        public static final String PACKAGE_NAME = "com.android.ImportDBTest";//包名
        public static final String DB_PATH = "/data"
                        + Environment.getDataDirectory().getAbsolutePath() + "/"
                        + PACKAGE_NAME;  //在手机里存放数据库的位置

        private SQLiteDatabase database;
        private Context context;

        DBManager(Context context) {
                this.context = context;
        }

        public void openDatabase() {
                this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
        }

        private SQLiteDatabase openDatabase(String dbfile) {
                try {
                        if (!(new File(dbfile).exists())) {  //判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库
                                InputStream is = this.context.getResources().openRawResource(
                                                R.raw.myDatabase); //欲导入的数据库
                                FileOutputStream fos = new FileOutputStream(dbfile);
                                byte[] buffer = new byte[BUFFER_SIZE];
                                int count = 0;
                                while ((count = is.read(buffer)) > 0) {
                                        fos.write(buffer, 0, count);
                                }
                                fos.close();
                                is.close();
                        }
                        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
                                        null);
                        return db;
                } catch (FileNotFoundException e) {
                        Log.e("Database", "File not found");
                        e.printStackTrace();
                } catch (IOException e) {
                        Log.e("Database", "IO exception");
                        e.printStackTrace();
                }
                return null;
}

 

然后在需要用到数据库的时候,用实例化一个DatabaseManager类,调用其openDatabase方法就可以返回一个SQLiteDatabase对象了..如下:

 

SQLiteDatabase db = new DBManager(this).openDatabase();

 

posted on 2011-12-12 14:59  yingql  阅读(1596)  评论(1)    收藏  举报

导航