chrisonline chrisonline - 5 months ago 138
Android Question

Backup and restore SQLite database to sdcard

How can I backup my database to the sdcard automatically in my app?
And afterward, how do I restore it?

Answer

Here is my code:

    // Local database
    InputStream input = new FileInputStream(from);

    // create directory for backup
    File dir = new File(DB_BACKUP_PATH);
    dir.mkdir();

    // Path to the external backup
    OutputStream output = new FileOutputStream(to);

    // transfer bytes from the Input File to the Output File
    byte[] buffer = new byte[1024];
    int length;
    while ((length = input.read(buffer))>0) {
        output.write(buffer, 0, length);
    }

    output.flush();
    output.close();
    input.close();
Comments