Android Raw数据库导入实现
面试中常出现此类问题:
怎样把SQLite数据库(例如dictionary.db)打包进APK并随应用发布?
解决方案是将该文件放入/res/raw目录。此目录下的文件在编译时不会被压缩,从而允许程序直接提取,同时系统会为该资源生成唯一的ID。
接下来需要解决的是,如何将从raw目录读取到的数据库文件,写入到已安装程序的内部存储database目录中?
复制代码 代码如下: public void imporDatabase() { //存放数据库的目录 String dirPath="/data/data/com.hkx.wan/databases"; File dir = new File(dirPath); if(!dir.exists()) { dir.mkdir(); } //数据库文件 File file = new File(dir, "abc.db"); try { if(!file.exists()) { file.createNewFile(); } //加载需要导入的数据库 InputStream is = this.getApplicationContext().getResources().openRawResource(R.raw.db_weather); FileOutputStream fos = new FileOutputStream(file); byte[] buffere=new byte[is.available()]; is.read(buffere); fos.write(buffere); is.close(); fos.close();
}catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); } }