如何将SQLite数据库与apk文件一起发布

可以将XX.db文件复制到Eclipse Android工程中的res\raw目录中,如图1所示。所有在res\raw目录中的文件不会被压缩,这样可以直接提取该目录中的文件。

使用openDatabase方法来打开数据库文件,如果该文件不存在,系统会自动创建/sdcard/dictionary目录,并将res\raw目录中的 XX.db文件复制到/sdcard/dictionary目录中。openDatabase方法的实现代码如下:这里以dictionary.db为例

[java]  view plain copy
  1. private SQLiteDatabase openDatabase()  
  2.   {  
  3.       try  
  4.       {  
  5.           // 获得dictionary.db文件的绝对路径  
  6.           String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;  
  7.           File dir = new File(DATABASE_PATH);  
  8.           // 如果/sdcard/dictionary目录中存在,创建这个目录  
  9.           if (!dir.exists())  
  10.               dir.mkdir();  
  11.           // 如果在/sdcard/dictionary目录中不存在  
  12.           // dictionary.db文件,则从res\raw目录中复制这个文件到  
  13.           // SD卡的目录(/sdcard/dictionary)  
  14.           if (!(new File(databaseFilename)).exists())  
  15.           {  
  16.               // 获得封装dictionary.db文件的InputStream对象  
  17.               InputStream is = getResources().openRawResource(R.raw.dictionary);  
  18.               FileOutputStream fos = new FileOutputStream(databaseFilename);  
  19.               byte[] buffer = new byte[8192];  
  20.               int count = 0;  
  21.               // 开始复制dictionary.db文件  
  22.               while ((count = is.read(buffer)) > 0)  
  23.               {  
  24.                   fos.write(buffer, 0, count);  
  25.               }  
  26.   
  27.               fos.close();  
  28.               is.close();  
  29.           }  
  30.           // 打开/sdcard/dictionary目录中的dictionary.db文件  
  31.           SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(  
  32.                   databaseFilename, null);  
  33.           return database;  
  34.       }  
  35.       catch (Exception e)  
  36.       {  
  37.       }  
  38.       return null;  
  39.   }  

 在openDatabase方法中使用了几个常量,这些常量是在程序的主类(Main)中定义的,代码如下:
[java]  view plain copy
  1. public class Main extends Activity implements OnClickListener, TextWatcher  
  2. {  
  3.     private final String DATABASE_PATH = android.os.Environment  
  4.             .getExternalStorageDirectory().getAbsolutePath()  
  5.             + "/dictionary";  
  6.     private final String DATABASE_FILENAME = "dictionary.db";  
  7. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值