将Asset中的数据库文件拷贝出来使用

时间:2022-11-10 13:35:38

设置保存路径

private final static String DATABASE_PATH
= "/data"+ Environment.getDataDirectory().getAbsolutePath()+"/"+PACKAGE_NAME+"/database";

拷贝文件

public synchronized void  init(final Context context, final InitCallback callback){
new Thread(new Runnable() {
@Override
public void run() {
String databaseFilename = DATABASE_PATH + "/address.db";
File dir = new File(DATABASE_PATH);
LogW.out(DATABASE_PATH);
if (!dir.exists())
dir.mkdir();
if (!(new File(databaseFilename)).exists()) {
try {
// InputStream is = context.getResources().openRawResource(R.raw.address);
InputStream is = context.getResources().getAssets().open("address.db");
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte[] buffer = new byte[2048];
int i = 0;
while ((i = is.read(buffer)) > 0) {
fos.write(buffer, 0, i);
}
fos.flush();
fos.close();
is.close();
} catch (IOException e) {
new File(databaseFilename).delete();
db = null;
callback.onError(e);
return;
}
}
db = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
callback.onSucess();
}
}).run();
}