·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> Android开发 >> android实现raw文件夹导入数据库代码

android实现raw文件夹导入数据库代码

作者:佚名      Android开发编辑:admin      更新时间:2022-07-23

有这样一道面试题:

如何将SQLite数据库(dictionary.db文件)与apk文件一起发布?


   答: 把这个文件放在/res/raw目录下即可。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();
     }
    }