1

我正在使用这种方法将我的 db 文件复制到 sd car 请告诉我 sdcard 上的文件是否已经存在,那么它将替换还是不会复制?

public boolean copyDbToSDCard() {
        boolean success = false;
        String SDCardPath = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        final String DBPATH = SDCardPath + "/BD/";
        final String DBNAME = "Mydb3.db";
        this.getReadableDatabase();
        File directory = new File(DBPATH);
        if (!directory.exists())
            directory.mkdir();
        close();

        try {
            InputStream mInput = new FileInputStream(DB_PATH + DB_NAME);
            OutputStream mOutput = new FileOutputStream(DBPATH + DBNAME);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = mInput.read(buffer)) > 0) {
                mOutput.write(buffer, 0, length);
            }
            mOutput.flush();
            mOutput.close();
            mInput.close();
            success = true;
        } catch (Exception e) {
            Toast.makeText(myContext,
                    "copyDbToSDCard Error : " + e.getMessage(),
                    Toast.LENGTH_SHORT).show();
            e.fillInStackTrace();
        }
        return success;
    }
4

2 回答 2

1

您可以检查数据库是否可用?

像这样

checkDB()
{
try{
      SQLiteDatabase   dbe = SQLiteDatabase.openDatabase("selectedFilePath", null,0);
        Log.d("opendb","EXIST");
        dbe.close();
         // DB exits then delete
        File file = new File(selectedFilePath);
        boolean deleted = file.delete(); <--- this will help you to delete DB

    }
    catch(Exception e)
    {
         // DB not exits code to copy database
    }
 }
于 2012-06-04T11:40:06.627 回答
1

编码:

OutputStream mOutput = new FileOutputStream(DBPATH + DBNAME);

mOutput.write(buffer, 0, length);

使得如果文件存在,它将用新数据替换文件的内容

于 2012-06-04T11:43:51.693 回答