-
Project-app-main文件夾下new一個assets folder,如圖:
準備好的數據庫文件直接復制粘貼過去。
- 用代碼把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);
}
}
}
- 用的時候直接:
- run
end: 查看一下數據庫的路徑,發現出現我們要的數據庫了。
另外,這個導入的數據庫是可以用GreenDao的,只要把對應的id和property都正確的生成就可以了。