導入本地SQLite文件

借鑒自 讀取assets目錄下的數據庫文件

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


  2. 準備好的數據庫文件直接復制粘貼過去。

  1. 用代碼把assets路徑下的該文件用I/O的方式寫入對應包名的路徑下,代碼如下:
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 {
            //不存在則復制粘貼到該路徑下
            File path = new File(pathStr);
            if (path.mkdir()) {
                Log.d("tag", "創建Path成功");
            } else {
                Log.d("tag", "創建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: 查看一下數據庫的路徑,發現出現我們要的數據庫了。

另外,這個導入的數據庫是可以用GreenDao的,只要把對應的id和property都正確的生成就可以了。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容