启动Android App时,动态将Sqlite数据库文件导入到手机中类方法

package com.aqioo.db;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.aqioo.R;
 

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

//在res文件夹下新建 raw 文件夹
//数据库文件放在 
es
aw	est.db
//在调用Sqlite的操作前实例化此类即可
//code by:博客园-曹永思
public class ImportDbFileToPhone {
    //        /data/data/名称空间(com.aqioo)/databases
    private static final String DATABASE_PATH = "/data/data/com.aqioo/databases";

    private static final int DATABASE_VERSION = 0;

    private static final String DATABASE_NAME = "test.db";//数据库

    private static String outFileName = DATABASE_PATH + "/" + DATABASE_NAME;

    private Context context;

    private SQLiteDatabase database;

    public ImportDbFileToPhone(Context context) {
        this.context = context;

        File file = new File(outFileName);
        if (file.exists()) {
            database = SQLiteDatabase.openOrCreateDatabase(outFileName, null);
            if (database.getVersion() != DATABASE_VERSION) {
                database.close();
                file.delete();
            }
        }
        try {
            buildDatabase();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void buildDatabase() throws Exception {
        InputStream myInput = context.getResources().openRawResource(
                R.raw.aqiooapp);
        File file = new File(outFileName);

        File dir = new File(DATABASE_PATH);
        if (!dir.exists()) {
            if (!dir.mkdir()) {
                throw new Exception("创建失败");
            }
        }

        if (!file.exists()) {
            try {
                OutputStream myOutput = new FileOutputStream(outFileName);

                byte[] buffer = new byte[1024];
                int length;
                while ((length = myInput.read(buffer)) > 0) {
                    myOutput.write(buffer, 0, length);
                }
                myOutput.close();
                myInput.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
    
}

 欢迎转载,转载请注明出处,希望帮到更多人。

原文地址:https://www.cnblogs.com/yonsy/p/3216520.html