android studio 使用外部sqlite数据库文件

Android studio需要将assets目录建在main项目下。即和Java,res等文件夹是同级的,数据库文件放在assets目录下。

这里说一下网上有的说res下raw目录,这里说一下区别:

assets:不会在R.java文件下生成相应的标记,assets文件夹可以自己创建文件夹,必须使用AssetsManager类进行访问,存放到这里的资源在运行打包的时候都会打入程序安装包中

raw:会在R.java文件下生成标记,这里的资源会在运行打包操作的时候判断哪些被使用到了,没有被使用到的文件资源是不会打包到安装包中的

res/raw和assets文件夹来存放不需要系统编译成二进制的文件。

具体步骤
在main目录下创建assets目录,把.db文件复制到文件夹下(android studio在project下就可以找到main目录)

在这里插入图片描述
第二部要把文件复制到手机上,这里用IO实现

public class DBFile {
    //数据库文件名
    private final String DB_NAME = "fileName.db";

    private Context context;

    public DBFile(Context context) {
        this.context = context;
    }

    // 复制和加载区域数据库中的数据
    public String CopyDBFile() throws IOException {

        // 第一次运行应用程序时,加载数据库到data/data/当前包的名称/database/<db_name>
        //获取准确的路径,context.getPackageName()得到包名
        File dir = new File("data/data/" + context.getPackageName() + "/databases");
        //如果文件夹不存在创建文件
        if (!dir.exists() || !dir.isDirectory()) {
            dir.mkdir();
        }
        //声明文件
        File file = new File(dir, DB_NAME);
        //输入流
        InputStream inputStream = null;
        //输出流
        OutputStream outputStream = null;
        //如果不存在,通过IO流的方式,将assets目录下的数据库文件,写入到手机中。
        if (!file.exists()) {
            try {
                //创建文件
                file.createNewFile();
                //通过路径加载文件
                inputStream = context.getClass().getClassLoader().getResourceAsStream("assets/" + DB_NAME);
                //输出到文件
                outputStream = new FileOutputStream(file);

                byte[] buffer = new byte[1024];
                int len;
                //按字节写入
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }


            } catch (IOException e) {
                e.printStackTrace();

            } finally {
                //关闭资源
                if (outputStream != null) {
                   
                    outputStream.flush();
                    outputStream.close();

                }
                if (inputStream != null) {
                    inputStream.close();
                }

            }

        }

        return file.getPath();
    }

在初始界面onCreate里加入以下两句

 DBFile dbFile = new DBFile(WelcomeActivity.this);
 dbFile.CopyDBFile();

这里就大功告成了,运行程序,查看虚拟机内部文件在 data/data/项目包路径/databases 刷新一下就可以看到 .db 文件了。

使用方法

private void initView() {
        //获取路径
        String databases_path = getDatabasePath("poetry.db").toString();
        //代开数据库
        SQLiteDatabase database = SQLiteDatabase.openDatabase(databases_path, null, SQLiteDatabase.OPEN_READONLY);
        //sql语句
        String sql = "select * from collection_kinds where name like ?";
        //条件
        String[] str = {"%节%"};
        //执行查询
        SQLiteCursor cursor = (SQLiteCursor) database.rawQuery(sql, str);
        //移到第一位
        cursor.moveToFirst();
        for (int i = 0; i < cursor.getCount(); i++) {
            //获取路径
            System.out.println(cursor.getInt(0) + "   " + cursor.getString(1));
            //移动到下一位
            cursor.moveToNext();
        }
    }

大功告成!!!

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用 Android 中的 SQLiteDatabase 类来实现外部 SQLite 数据库的批量插入。以下是一个示例代码: ```java // 打开外部数据库 SQLiteDatabase externalDB = SQLiteDatabase.openDatabase("/sdcard/mydatabase.db", null, SQLiteDatabase.OPEN_READONLY); // 打开内部数据库 SQLiteDatabase internalDB = getWritableDatabase(); // 查询外部数据库中的数据 Cursor cursor = externalDB.rawQuery("SELECT * FROM mytable", null); // 开始批量插入 internalDB.beginTransaction(); try { while (cursor.moveToNext()) { // 从外部数据库中读取数据 int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); // 插入到内部数据库中 ContentValues values = new ContentValues(); values.put("id", id); values.put("name", name); values.put("age", age); internalDB.insert("mytable", null, values); } internalDB.setTransactionSuccessful(); } finally { internalDB.endTransaction(); } // 关闭游标和数据库连接 cursor.close(); externalDB.close(); internalDB.close(); ``` 在上面的代码中,我们首先打开外部数据库,然后查询其中的数据。接着,我们打开内部数据库,并使用 `beginTransaction()` 方法开始一个事务。在事务中,我们循环读取外部数据库中的数据,并将其插入到内部数据库中。最后,我们使用 `setTransactionSuccessful()` 方法标记事务成功,并使用 `endTransaction()` 方法结束事务。最后,我们关闭游标和数据库连接。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值