借鑒自 讀取assets目錄下的數(shù)據(jù)庫文件
-
Project-app-main文件夾下new一個assets folder,如圖:
準(zhǔn)備好的數(shù)據(jù)庫文件直接復(fù)制粘貼過去。

- 用代碼把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);
}
}
}
- 用的時候直接:

- run
end: 查看一下數(shù)據(jù)庫的路徑,發(fā)現(xiàn)出現(xiàn)我們要的數(shù)據(jù)庫了。
另外,這個導(dǎo)入的數(shù)據(jù)庫是可以用GreenDao的,只要把對應(yīng)的id和property都正確的生成就可以了。
