复制到SD卡时,数据库部分复制

时间:2014-02-21 04:31:54

标签: android sqlite

我正在创建一个使用现成SQLiteDatabase的应用。我正在选择用户将数据库复制到SD卡或手机内存中。将数据库复制到手机内存时,以下代码可以正常工作。 26.5 MB数据库完全复制到手机内存中。但是如果使用相同的代码在sd卡中复制,则只复制数据库的一部分,即只复制一个名为android_metadata的表。

private void copyDatabase(String storage) {

    try {
        //DB_NAME  is defined in the class
        //DB_PATH refers to the phone directory path.
        InputStream in = myContext.getAssets().open(DB_NAME);
        File sd = Environment.getExternalStorageDirectory();
        File sdCardPath = new File(sd, DB_NAME);
        File phonePath = new File(DB_PATH + DB_NAME);
        OutputStream os = null;
        if (storage.equalsIgnoreCase("sd"))
            os = new FileOutputStream(sdCardPath);
        else if (storage.equalsIgnoreCase("phone"))
            os = new FileOutputStream(phonePath);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = in.read(buffer)) != -1) {
            os.write(buffer, 0, length);

        }

        os.flush();
        os.close();
        in.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

问题是虽然数据库是在SD卡内存中创建的,但不会复制完整的数据库。这样创建的数据库大小只有3.4 Mb,而原始数据库的大小是26.5 Mb,我通过Eclipse中的File Explorer视图检查了它。

有什么建议吗?

修改 当我直接从assets文件夹复制数据库时,我无法获取FileInputStreamFileChannel对象。我只能从InputStream资源中获取assets个对象。

2 个答案:

答案 0 :(得分:0)

请尝试给定的功能,希望它能为您提供帮助

public void copyDatabse(String databaseName) {
        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "//data//"+getPackageName()+"//databases//"+databaseName+"";
                String backupDBPath = "backupname.db";
                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);

                if (currentDB.exists()) {
                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
        } catch (Exception e) {

        }
    }

并拨打copyDatabse("databasename");

也请访问

Trying to Copy SQLite DB from data to SD card

答案 1 :(得分:0)

此代码应该完成这项工作:

void copyDataBase() throws IOException {

        String outFileName = DB_PATH + DB_NAME;

        OutputStream myOutput = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;

        InputStream myInput = myContext.getAssets().open("mydb.sqlite");
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
        myInput.close();

        myOutput.flush();
        myOutput.close();

    }

其中outFileName将保存您要存储在SD卡上的位置