首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Android外部数据库的引用

Android外部数据库的引用

作者头像
计蒙不吃鱼
发布2025-06-12 15:17:44
发布2025-06-12 15:17:44
1470
举报
文章被收录于专栏:Android开发Android开发

情景:有现成的数据库,需要在项目中使用。

1.将数据库拷贝到main文件夹下的assets文件夹中(assets文件夹需自己创建,且文件夹名称必须为assets,否则AS无法编译)

2.一般是在APP的引导界面将已有数据库拷贝到App的目录中去

3.对数据库进行操作。

将数据库拷贝到App中的方法如下

代码语言:javascript
复制
    private void copydatabase(String dbname) {
        //getFilesDir:拿到data-data当前目录下的files文件夹的绝对路径
        File file = new File(getFilesDir(), dbname);
        if (!file.exists()){//判断db是否存在
            AssetManager assets = getAssets();
            FileOutputStream fos = null;
            InputStream is = null;
            try {
                //拿到输入流
                is = assets.open(dbname);
                //读写
                fos = new FileOutputStream(file);
                //缓冲区
                byte[] b = new byte[1024];
                int len = -1;
                while ((len = is.read(b)) != -1) {
                    fos.write(b, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-06-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档