天天看點

啟動Android App時,動态将Sqlite資料庫檔案導入到手機中類方法 - 曹永思

啟動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 檔案夾
//資料庫檔案放在 \res\raw\test.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();
            }

        }
    }
    
}      

 歡迎轉載,轉載請注明出處,希望幫到更多人。

啟動Android App時,動态将Sqlite資料庫檔案導入到手機中類方法 - 曹永思