将sqlite db保存在外部存储器中

时间:2015-06-01 06:22:05

标签: android sqlite android-external-storage

我想将sqlite db文件保存在外部存储器中。

我编写代码保存在内部存储器中,如下所示。但我想提取" xxx.db "在运行时并检查我的数据库字段是否已保存。

的manifest.xml

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

DBHelper.java

private static String DB_PATH           =   "data/data/com.example.myApp/databases/";
private static final String DATABASE_TABLE  =   "myDB";
private static final int DATABASE_VERSION   =    1;
private static final String DATABASE_NAME   =   "mydb.db";

public void createDatabase() throws IOException{

        boolean doesDbExist = checkDatabase();

        if(doesDbExist){
            Toast.makeText(ourContext, "DB Already Created", Toast.LENGTH_SHORT).show();
        }else{
            this.getReadableDatabase();
            try{
                copyDatabase();
            }catch(Exception e){
                Log.d("DBError", "Copy DB error");
            }
            Toast.makeText(ourContext, "New DB created.", Toast.LENGTH_SHORT).show();
        }
    }

    private void copyDatabase() throws IOException{
            //Open your local db as the input stream
            InputStream myInput     =   ourContext.getAssets().open(DATABASE_NAME);

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

            //Open the empty db as the output stream
            OutputStream myOutput   =   new FileOutputStream(outFileName);

            //transfer bytes from the inputfile to the outputfile
            byte buffer[]           =   new byte[1024];

            int len;

            while ((len = myInput.read(buffer))>0) {

                myOutput.write(buffer, 0, len);

            }
            // Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();

        }

请帮助我并建议我进行必要的更改。

1 个答案:

答案 0 :(得分:0)

以下是如何轻松将数据库保存到SD卡的方法:

private void backup() throws IOException {
        File currentFile = new File(Environment.getDataDirectory(), "//data//" + activity.getPackageName() + "//databases//" + DATABASE_NAME);

        File backupFile = new File(Environment.getExternalStorageDirectory(), DatabaseHandler.DATABASE_NAME);
        backupFile.delete();
        backupFile.createNewFile();

        FileInputStream fis = new FileInputStream(currentFile);
        FileOutputStream fos = new FileOutputStream(backupFile);

        ByteStreams.copy(fis, fos);

        fis.close();
        fos.close();
    }

请注意,我使用了Guava的ByteStreams。