如何从SD卡使用sqlite数据库?

时间:2014-02-18 10:05:35

标签: android sqlite memory android-sdcard developer-tools

我在访问数据库时遇到了麻烦。我的SD卡上有一个数据库,而不是我的资产。如何配置?我可以使用这段代码吗?

private void copyDataBase() throws IOException {
InputStream myInput = context.getExternalFilesDir(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}

尝试此代码时出现错误

1 个答案:

答案 0 :(得分:0)

SQLite将始终仅在您的应用程序上下文中创建数据库。它将创建一个名为databases的文件夹,并仅将所有数据库保存在该文件夹中。因此,您必须将数据库从SD卡复制到您的应用程序数据库

private void copyDataBaseFromSdCard() 
{
    try
    {
        String DB_PATH = "data/data/" + getPackageName() + "/databases/";
        String DB_NAME = "testcopy.db";

        String yourDbFileNamePresentInSDCard = "/mnt/sdcard/test.db";
        File file = new File(yourDbFileNamePresentInSDCard);
        // Open your local db as the input stream
        InputStream myInput = new FileInputStream(file);

        // Path to created empty db
        String outFileName = DB_PATH + DB_NAME;

        // Opened assets database structure
        OutputStream myOutput = new FileOutputStream(outFileName);

        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }
    catch(Exception e)
    {

    }
}

    private SQLiteDatabase getDB()
{
     String DB_NAME = "testcopy.db";
    return openOrCreateDatabase(DB_NAME, SQLiteDatabase.OPEN_READWRITE, null);
}