DB文件要放在Assets文件夹下,封装一个工具类,如下:
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 }