[Android]如何导入已有的外部数据库

平常一些数据都是在数据库文件写好的,但是安卓却没有直接导入的功能。

android系统下数据库一般存放在 /data/data/com.*.*(package name)/ 目录下,所以我们需要做的是把已有的数据库传入那个目录下。

操作方法是用FileInputStream读取原数据库,再用FileOutputStream把读取到的东西写入到那个目录。


Android studio工程为例

操作方法:1. 在java和res的同级目录下,新建assets目录,把原数据库platform_home.db文件(db文件可以用SQLiteExpertPers.exe工具查看和编辑)放在在项目源码的 assets 目录下


2、编写拷贝资源文件的方法copyAssetsFile,注意:资源文件的获取方法如下:

context.getClass().getClassLoader()
                    .getResourceAsStream("assets/" + fileNmae); //读入资源文件

/**
 * 复制资源文件
 * @param context
 * @param desPath
 * @param fileNmae
 */
public static void copyAssetsFile(Context context, String desPath,String fileNmae) {
    try {
        int bytesum = 0;
        int byteread = 0;
        File desfile = new File(desPath+"/"+fileNmae);
        if (!desfile.exists()) { //文件不存在时
            InputStream inStream = context.getClass().getClassLoader()
                    .getResourceAsStream("assets/" + fileNmae); //读入资源文件
            FileOutputStream fs = new FileOutputStream(desPath+"/"+fileNmae);
            byte[] buffer = new byte[4096];
            int length;
            while ( (byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread; //字节数 文件大小
                fs.write(buffer, 0, byteread);
                fs.flush();
            }
            fs.close();
            inStream.close();
            LogUtil.i("数据库已拷贝!");
        }
    }
    catch (Exception e) {
        LogUtil.i("复制单个文件操作出错");
        e.printStackTrace();

    }

}

3、如果拷贝成功的话,DDMS可以看到下图,然后获取数据库。

private SQLiteDatabase database;

database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/" + DBManager.DB_NAME, null);


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

产品大道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值