获取资产文件夹中的SQLite路径 [英] Get the SQLite path within the Assets Folder

查看:111
本文介绍了获取资产文件夹中的SQLite路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发应用程序,在这里遇到了两个问题:

  1. 如何打开存储在资产文件夹中的SQLite数据库?我应使用什么路径访问应用程序中的资产文件夹?这是我到目前为止的内容:

    path = "file:///asset_folder/database.dat";
    SQLiteDatabase db = null;
    db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
    

  2. 在安装应用程序或首次运行期间,如何将文件复制到内部存储器(/data/data/...)?我想在第一次运行时将资产文件夹内的文件夹复制到内部存储器中.

任何建议将不胜感激.

解决方案

我遇到了同样的问题,因此我将db文件移至res/raw文件夹,并按如下方式进行访问:

InputStream inputStream = getBaseContext().getResources().openRawResource(R.raw.mySQLiteFile);

然后,我尝试将文件移到/data/data/com.mydomain.www/databases/文件夹中,但是由于目标路径不存在,所以我会得到一个例外,所以我做了File(destPath).getParentFile().mkdir();

从那里,我调用了复制db方法将数据库传输到目标.

public void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
        inputStream.close();
        outputStream.close();
    }

InputStream是db文件,OutputStream是FileOutputStream(destPath).

I'm developing an application and I've run into two problems here:

  1. How can I open an SQLite database which is stored in the assets folder? What path do I use to access the assets folder in my application? Here's what I have so far:

    path = "file:///asset_folder/database.dat";
    SQLiteDatabase db = null;
    db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
    

  2. How can I copy a file to the internal memory (/data/data/...) during the installation of my application or during the first run? I want to copy a folder inside the assets folder into the internal memory during the first run.

Any suggestions would be greatly appreciated.

解决方案

I was having the same problem, so I moved the db file to the res/raw folder, and accessed it like so:

InputStream inputStream = getBaseContext().getResources().openRawResource(R.raw.mySQLiteFile);

Then I tried to move the file into the /data/data/com.mydomain.www/databases/ folder, but I would get an exception because the destination path didn't exist, so I did File(destPath).getParentFile().mkdir();

From there, I called a copy db method to transfer the db to the destination.

public void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
        inputStream.close();
        outputStream.close();
    }

InputStream is the db file, OutputStream is the FileOutputStream(destPath).

这篇关于获取资产文件夹中的SQLite路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆