1

I'm copying my db file to sd car using this methode please tell me if file at sdcard is already existing then whether it will replace or will not copy?

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;
    }
Trikaldarshiii
  • 11,174
  • 16
  • 67
  • 95
  • 4
    How about testing your code instead of asking if it works? It is almost way faster and does not waste our time – WarrenFaith Jun 04 '12 at 11:34

2 Answers2

1

You can check is database available or not ?

like this

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
    }
 }
MAC
  • 15,799
  • 8
  • 54
  • 95
1

the code:

OutputStream mOutput = new FileOutputStream(DBPATH + DBNAME);

and

mOutput.write(buffer, 0, length);

makes that if the file exists it will replace the content of the file with the new data

magodiez
  • 741
  • 2
  • 10
  • 23