从外部存储Android打开数据库

时间:2016-04-18 02:50:28

标签: android sqlite

我之前在我的apps资源文件夹中存储了一个sqlite数据库,但现在已将数据库移动到外部存储。

我以前的copyDatabase()方法看起来像这样。

private void copyDataBase() throws IOException {
        InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
        OutputStream myOutput = new FileOutputStream(DB_PATH);
        byte[] buffer = new byte[AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT];
        while (true) {
            int length = myInput.read(buffer);
            if (length > 0) {
                myOutput.write(buffer, 0, length);
            } else {
                myOutput.flush();
                myOutput.close();
                myInput.close();
                return;
            }
        }
    }

问题是我不确定如何创建InputStream以从外部存储打开数据库。我似乎无法找到相当于myContext.getAssets().open(DATABASE_NAME);

的外部存储空间

当前数据库路径:

DB_PATH = Environment.getExternalStorageDirectory().getPath().toString()+"/SoulInfoDatabase/BB2SoulDatabase.db";

1 个答案:

答案 0 :(得分:1)

第1步:在App Manifesto文件中授予存储权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

第2步:将数据库复制到自定义SD卡路径

private void copyDataBase() throws IOException {
    // Open your local db as the input stream
    InputStream myInput = context.getAssets().open(DB_NAME);

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

    // Open the empty db as the output stream
    new File(outFileName).createNewFile();
    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();
}

步骤3:然后打开您的数据库:

try {
        db = SQLiteDatabase.openDatabase(DB_PATH + "/" + DB_NAME, null,
                SQLiteDatabase.OPEN_READWRITE
                        | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

<强> WHERE

String filePath =  Environment.getExternalStorageDirectory().getAbsolutePath() + "/SoulInfoDatabase";
File file = new File(filePath);
if(!file.exists()){
    file.mkdirs();
}

DB_PATH = filePath; DB_NAME =“BB2SoulDatabase.sqlite”;