導(dǎo)入本地SQLite文件

借鑒自 讀取assets目錄下的數(shù)據(jù)庫文件

  1. Project-app-main文件夾下new一個assets folder,如圖:


  2. 準(zhǔn)備好的數(shù)據(jù)庫文件直接復(fù)制粘貼過去。

  1. 用代碼把assets路徑下的該文件用I/O的方式寫入對應(yīng)包名的路徑下,代碼如下:
public class DataBaseManager {
    String filePath = "data/data/com.solory.william.myweather/databases/my_db.db";
    String pathStr = "data/data/com.solory.william.myweather/databases";

    SQLiteDatabase sqLiteDatabase;

    public SQLiteDatabase openDataBase(Context context) {
        File jhPath = new File(filePath);
        if (jhPath.exists()) {
            //存在則直接打開
            return SQLiteDatabase.openOrCreateDatabase(jhPath, null);
        } else {
            //不存在則復(fù)制粘貼到該路徑下
            File path = new File(pathStr);
            if (path.mkdir()) {
                Log.d("tag", "創(chuàng)建Path成功");
            } else {
                Log.d("tag", "創(chuàng)建Path失敗");
            }
            try {
                AssetManager assetManager = context.getAssets();
                InputStream is = assetManager.open("my_db.db");
                FileOutputStream fos = new FileOutputStream(jhPath);
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.flush();
                fos.close();
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            return openDataBase(context);
        }
    }
}
  1. 用的時候直接:
  1. run

end: 查看一下數(shù)據(jù)庫的路徑,發(fā)現(xiàn)出現(xiàn)我們要的數(shù)據(jù)庫了。

另外,這個導(dǎo)入的數(shù)據(jù)庫是可以用GreenDao的,只要把對應(yīng)的id和property都正確的生成就可以了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容