我有一个扩展 ProviderTestCase2<> 的测试类。
我想用一些 .db 文件中的数据填充这个测试类数据库。
是否有一些特殊的方法可以将一些 .db 文件推送到 ProviderTestCase2 的模拟上下文中?
否则哪种方式更容易从 .db 文件填充数据库?!
非常感谢!!
我有一个扩展 ProviderTestCase2<> 的测试类。
我想用一些 .db 文件中的数据填充这个测试类数据库。
是否有一些特殊的方法可以将一些 .db 文件推送到 ProviderTestCase2 的模拟上下文中?
否则哪种方式更容易从 .db 文件填充数据库?!
非常感谢!!
如何从 SD 卡或类似的东西中复制一个预先存在的 .db 文件?这是一段将为您完成此任务的快速代码:
private void importDBFile(File importDB) {
String dataDir = Environment.getDataDirectory().getPath();
String packageName = getPackageName();
File importDir = new File(dataDir + "/data/" + packageName + "/databases/");
if (!importDir.exists()) {
Toast.makeText(this, "There was a problem importing the Database", Toast.LENGTH_SHORT).show();
return;
}
File importFile = new File(importDir.getPath() + "/" + importDB.getName());
try {
importFile.createNewFile();
copyDB(importDB, importFile);
Toast.makeText(this, "Import Successful", Toast.LENGTH_SHORT).show();
} catch (IOException ex) {
Toast.makeText(this, "There was a problem importing the Database", Toast.LENGTH_SHORT).show();
}
}
private void copyDB(File from, File to) throws IOException {
FileChannel inChannel = new FileInputStream(from).getChannel();
FileChannel outChannel = new FileOutputStream(to).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
希望这适用于您的场景