DB文件要放在Assets文件夾下,封裝一個工具類,以下:java
1 package com.XX.DB; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 8 import android.content.Context; 9 import android.content.res.AssetManager; 10 import android.database.sqlite.SQLiteDatabase; 11 import android.os.Environment; 12 13 /** 14 * SQLite幫助類:打開外部DB文件 15 * 16 * @author XX 17 * @since 2015年7月8日 11:20:28 18 */ 19 public class DBManager { 20 public static SQLiteDatabase mDatabase = null; 21 private static Context mContext; 22 /** 23 * 數據庫名字 24 */ 25 public static String DB_NAME = "ExternalDB.db"; 26 /** 27 * 內存DB文件存儲路徑 28 */ 29 public static String DB_PATH = ""; 30 private static int BUFFER_SIZE = 40000; 31 32 /** 33 * 單例模式:獲取DBManager實例 34 * 35 * @param context 36 * @return 37 */ 38 public static SQLiteDatabase getInstance(Context context) { 39 mContext = context; 40 DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() 41 + "/" + mContext.getPackageName() + "/databases"; 42 if (mDatabase == null) { 43 synchronized (DBManager.class) { 44 mDatabase = openDatabase(); 45 } 46 } 47 return mDatabase; 48 } 49 50 /** 51 * 獲取數據庫 52 * 53 * @return 54 */ 55 public SQLiteDatabase getDatabase() { 56 return mDatabase; 57 } 58 59 /** 60 * 設置數據庫 61 * 62 * @param db 63 */ 64 public void setDatabase(SQLiteDatabase db) { 65 mDatabase = db; 66 } 67 68 /** 69 * 關閉數據庫 70 */ 71 public void closeDatabase() { 72 if (mDatabase != null) { 73 mDatabase.close(); 74 } 75 } 76 77 /** 78 * 從本地讀取DB文件 ,並加載到內存 79 * 80 * @param dB_PATH 81 * @return 82 */ 83 private static SQLiteDatabase openDatabase() { 84 try { 85 File file = new File(DB_PATH); 86 // 若是內存中不存在,則開始導入 87 if (!file.exists()) { 88 file.mkdirs(); 89 AssetManager manager = mContext.getAssets(); 90 InputStream is = manager.open(DB_NAME); 91 FileOutputStream fos = new FileOutputStream(DB_PATH + "/" 92 + DB_NAME); 93 byte[] buffer = new byte[BUFFER_SIZE]; 94 int count = 0; 95 while ((count = is.read(buffer)) > 0) { 96 fos.write(buffer, 0, count); 97 } 98 fos.close(); 99 is.close(); 100 } 101 SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH 102 + "/" + DB_NAME, null); 103 return db; 104 } catch (IOException e) { 105 e.printStackTrace(); 106 } 107 return null; 108 } 109 }