Android导入外部数据库可以将数据库直接复制到assets文件夹下面,然后通过输入流写入手机应用目录下,再去操作数据库。但是当数据库过大时,就会无法写入手机,这种情况下,可以借助Filesplit工具先将大数据库进行分割,然后分别建立输入流合并成一个大数据库写入手机。
将分割后的小数据库写入手机的方法可参考以下代码:
/**
* 如果数据库文件较大,使用FileSplit分割为小于1M的小文件
* 此例中分割为 huangli.db.0 huangli.db.1 ...
*/
//第一个文件名后缀
private static final int ASSETS_SUFFIX_BEGIN = 1;
//最后一个文件名后缀
private static final int ASSETS_SUFFIX_END = 56;
private boolean copyAssetsToFilesystem(String assetsSrc, String des){
LogUtil.d(tag, "Copy "+assetsSrc+" to "+des);
InputStream istream = null;
OutputStream ostream = null;
try{
AssetManager am = context.getAssets();
ostream = new FileOutputStream(des);
for (int i = ASSETS_SUFFIX_BEGIN; i < ASSETS_SUFFIX_END + 1; i++) {
LogUtil.d("huangli.db",i+"");
istream = am.open(assetsSrc+"."+i);
byte[] buffer = new byte[1024];
int length;
while ((length = istream.read(buffer))>0){
ostream.write(buffer, 0, length);
}
ostream.flush();
istream.close();
}
ostream.close();
LogUtil.d("copyAssetsToFilesystem.success");
}
catch(Exception e){
LogUtil.d("copyAssetsToFilesystem.error");
e.printStackTrace();
try{
if(istream!=null)
istream.close();
if(ostream!=null)
ostream.close();
}
catch(Exception ee){
ee.printStackTrace();
}
return false;
}
return true;
}