copy database File From Assets - Android Database

Android examples for Database:Database Backup

Description

copy database File From Assets

Demo Code


//package com.book2s;
import android.content.Context;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    public static void copyDBFileFromAssets(Context context, String dbName) {

        String databasePath = context.getApplicationInfo().dataDir
                + "/databases/" + dbName;

        try {/* w w  w . ja v  a 2  s .  com*/
            InputStream inputDataBaseFile = context.getAssets()
                    .open(dbName);
            OutputStream outputDataBaseFile = new FileOutputStream(
                    databasePath);

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

            while ((length = inputDataBaseFile.read(buffer)) > 0) {
                outputDataBaseFile.write(buffer, 0, length);
            }

            // Close the streams
            outputDataBaseFile.flush();
            outputDataBaseFile.close();
            inputDataBaseFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials